如何在ASP.NET中使用视图模型?

问题描述 投票:0回答:1

我想查看两个名为Nvram和ExecOut的表的数据。

** Nvram:**

using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SmartRouter.Domain
{
  public class Nvram
  {
    [Key, ForeignKey("SRouter")]
    public int NvramId { get; set; }
    [JsonProperty("wanConnectionMode")]
    public string ConnectionType { get; set; }
    [JsonProperty("WAN_MAC_ADDR")]
    public string IConfigMacAddress { get; set; }
    [JsonProperty("lan_gateway")]
    public string DefaultGateway { get; set; }

    [JsonProperty("wan_dhcp_hn")]
    public string HostName { get; set; }
    [JsonProperty("macCloneEnabled")]
    public string MacCloneEnable { get; set; }
    [JsonProperty("macCloneMac")]
    public string MacCloneMac { get; set; }
    [JsonProperty("wan_pppoe_user")]
    public string Username { get; set; }
    [JsonProperty("wan_pppoe_pass")]
    public string Password { get; set; }
    [JsonProperty("wan_pppoe_optime")]
    public string WanOperationMode { get; set; }
    [JsonProperty("wan_ipaddr")]
    public string WanIPAddress { get; set; }
    [JsonProperty("wan_netmask")]
    public string WanSubnetNetmask { get; set; }
    [JsonProperty("wan_gateway")]
    public string WanGatewayIP { get; set; }
    [JsonProperty("wan_primary_dns")]
    public string WanDNS1 { get; set; }
    [JsonProperty("wan_secondary_dns")]
    public string WanDNS2 { get; set; }
    [JsonProperty("lan_ipaddr")]
    public string LanIPAddress { get; set; }
    [JsonProperty("lan_netmask")]
    public string LanSubnetNetmask { get; set; }
    [JsonProperty("dhcpEnabled")]
    public bool? DHCPEnabled { get; set; }
    [JsonProperty("dhcpStart")]
    public string DHCPStart { get; set; }
    [JsonProperty("dhcpEnd")]
    public string DHCPEnd { get; set; }
    [JsonProperty("dhcpMask")]
    public string DHCPSubnetMask { get; set; }
    [JsonProperty("dhcpPriDns")]
    public string DHCPDNSPrimary { get; set; }
    [JsonProperty("dhcpSecDns")]
    public string DHCPDNSSecondary { get; set; }
    [JsonProperty("dhcpGateway")]
    public string DHCPGateway { get; set; }
    [JsonProperty("dhcpLease")]
    public string DHCPLeaseTime { get; set; }
    [JsonProperty("upnpEnabled")]
    public bool? UPnP { get; set; }
    [JsonProperty("radvdEnabled")]
    public bool? RouterAdvertisement { get; set; }
    [JsonProperty("WiFiOff")]
    public bool? WiFiOnOff { get; set; }
    [JsonProperty("WirelessMode")]
    public string NetworkMode { get; set; }
    [JsonProperty("SSID1")]
    public string SSID { get; set; }
    [JsonProperty("HideSSID")]
    public bool? BroadcastSSID { get; set; }
    [JsonProperty("NoForwardingBTNBSSID")]
    public bool? APIsolation { get; set; }
    [JsonProperty("Channel")]
    public int? Channel { get; set; }
    [JsonProperty("AutoChannelSelect")]
    public bool? AutomaticChannelSelection { get; set; }
    [JsonProperty("BGProtection")]
    public int? BGProtection { get; set; }
    [JsonProperty("BeaconPeriod")]
    public int? BeaconPeriod { get; set; }
    [JsonProperty("DtimPeriod")]
    public int? DTIMPeriod { get; set; }
    [JsonProperty("FragThreshold")]
    public string FragmentThreshold { get; set; }
    [JsonProperty("RTSThreshold")]
    public int? RTSThreshold { get; set; }
    [JsonProperty("TxPreamble")]
    public bool? EnablePeramble { get; set; }
    [JsonProperty("wmm_capable")]
    public bool? WMMEnabled { get; set; }
    [JsonProperty("APSDCapable")]
    public bool? EnableAPSD { get; set; }
    [JsonProperty("DLSCapable")]
    public bool? EnableDLS { get; set; }
    [JsonProperty("AuthMode")]
    public string SecurityMode { get; set; }
    [JsonProperty("EncrypType")]
    public string WPAAlgorithm { get; set; }
    [JsonProperty("WPAPSK1")]
    public string SecurityPassword { get; set; }
    [JsonProperty("Rekeyinterval")]
    public long? KeyRenewalinterval { get; set; }
    [Required]
    public virtual SRouter SRouter { get; set; }
  }
}

**执行:**

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartRouter.Domain
{
  public class ExecOut
  {
    [Key, ForeignKey("SRouter")]
    public int ExeOutId { get; set; }
    [JsonProperty("uname -sv")]
    public string BuildInfo{get;set;}

    [JsonProperty("uptime")]
    public string Uptime { get; set; }
    [JsonProperty("web 2860 sys wanIpAddr")]
    public string WANIPAddress { get; set; }
    [JsonProperty("web 2860 sys wanNetmask")]
    public string SubnetMask { get; set; }
    [JsonProperty("web 2860 sys wanGateway")]
    public string DefaultGateway { get; set; }
    [JsonProperty("web 2860 sys dns1")]
    public string PrimaryDNS { get; set; }
    [JsonProperty("web 2860 sys dns2")]
    public string SecondaryDNS { get; set; }
    [JsonProperty("eth_mac r lan")]
    public string LanMacAddress { get; set; }
    [JsonProperty("web 2860 sys dhcpClientList")]
    public string DHCPClientList { get; set; }
    [JsonProperty("web 2860 sys wanMacAddr")]
    public string WanMacAddr { get; set; }
    [Required]
    public virtual SRouter SRouter { get; set; }
  }
}

要获取两个表的数据,我创建了以下存储库:

using SmartRouter.Domain;
using SmartRouter.Persistance.Facade;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartRouter.Persistance.Repositories
{
  public class RouterInfoRepository : IRouterInfoRepository
  {
    private readonly RouterDBContext _srdbcontext;
    public RouterInfoRepository(RouterDBContext srdbcontext)
    {
      _srdbcontext = srdbcontext;
    }

    public dynamic GetRouterStatusByMac(string macAddress)
    {
      var nvramdata=_srdbcontext.Nvrams.Where(q => q.SRouter.MacAddress == macAddress).Select(s => new
      {
        s.ConnectionType,
        s.IConfigMacAddress,
        s.LanIPAddress,
        s.LanSubnetNetmask,
        s.DefaultGateway
      }).FirstOrDefault();
      var execdata = _srdbcontext.ExeOuts.Where(q => q.SRouter.MacAddress == macAddress).Select(e => new
      {
        e.BuildInfo,
        e.Uptime,
        e.WANIPAddress,
        e.SubnetMask,
        e.DefaultGateway,
        e.PrimaryDNS,
        e.SecondaryDNS,
        e.LanMacAddress
      }).FirstOrDefault();
      return new
      {
        nvramdata.ConnectionType,
        nvramdata.IConfigMacAddress,
        nvramdata.LanIPAddress,
        nvramdata.LanSubnetNetmask,
        nvramDefaltGateway = nvramdata.DefaultGateway,
        execdata.BuildInfo,
        execdata.Uptime,
        execdata.WANIPAddress,
        execdata.SubnetMask,
        exeDefaultGateway = execdata.DefaultGateway,
        execdata.PrimaryDNS,
        execdata.SecondaryDNS,
        execdata.LanMacAddress
      };
        //return result;
    }
  }
}

在上面的函数中,我从Nvram中获取了一些参数,并从ExecOut中获取了一些参数。

最后我在RouterController中使用这个存储库的功能

   public ActionResult Status()
        {
          using (RouterUnitOfWork uow = new RouterUnitOfWork())
          {
        IRouterInfoRepository routerrepository = new RouterInfoRepository(uow.CurrentObjectContext);
                ViewBag.routerinfodata = routerrepository.GetRouterStatusByMac("f8:b5:68:a0:10:1c");


                //var routerdata = new RouterStatusViewModel();
                //routerdata.ConnectionType=routerinfodata.ConnectionType;

            return View();
          }
        }

当我尝试在视图中打印值时:

<td>@ViewBag.routerinfodata.ConnectionType</td>

我收到以下错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'ConnectionType''

另一个困惑是:

我还为我选择的参数(来自Nvram和ExecOut)创建了一个视图模型,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RouterManagement.Models
{
    public class RouterStatusViewModel
    {

        public string BuildInfo { get; set; }
        public string Uptime { get; set; }
        public string ConnectionType { get; set; }

    public string WANIPAddress { get; set; }

    public string SubnetMask { get; set; }


    public string ExecDefaultGateway { get; set; }

    public string PrimaryDNS { get; set; }

    public string SecondaryDNS { get; set; }

    public string IConfigMacAddress { get; set; }

    public string LanIPAddress { get; set; }

    public string LanSubnetNetmask { get; set; }

    public string NvramDefaultGateway { get; set; }

    public string LanMacAddress { get; set; }



    }
}

我完成了上述任务,然后是指南。因为我是新人,所以我只是继续尝试理解我所做的每一步。除了视图模型,一切都很清楚。我看不到视图模型的使用。我的方法不对吗?我非常感谢您对ASP.NET开发人员的支持。提前致谢。

c# viewmodel
1个回答
2
投票

不确定哪个对象返回动态,因此您可能希望返回一些DataFromRepoDto对象(为该对象创建新类),其中您已分配了所有这些字段

DataFromRepoDto:

    public class DataFromRepoDto{
            public string ConnectionType {get;set;}
            public string IConfigMacAddress {get;set;}
            public string LanIPAddress {get;set;}

            //etc all needed fields with respective datatypes


    }   

您的方法已修改:

public DataFromRepoDto GetRouterStatusByMac(string macAddress)
{
  var nvramdata=_srdbcontext.Nvrams.Where(q => q.SRouter.MacAddress == macAddress).Select(s => new
  {
    s.ConnectionType,
    s.IConfigMacAddress,
    s.LanIPAddress,
    s.LanSubnetNetmask,
    s.DefaultGateway
  }).FirstOrDefault();
  var execdata = _srdbcontext.ExeOuts.Where(q => q.SRouter.MacAddress == macAddress).Select(e => new
  {
    e.BuildInfo,
    e.Uptime,
    e.WANIPAddress,
    e.SubnetMask,
    e.DefaultGateway,
    e.PrimaryDNS,
    e.SecondaryDNS,
    e.LanMacAddress
  }).FirstOrDefault();
  return new DataFromRepoDto
  {
    ConnectionType = nvramdata.ConnectionType,
    IConfigMacAddress = nvramdata.IConfigMacAddress,
    LanIPAddress = nvramdata.LanIPAddress,
    //etc...
  };
    //return result;
}

然后在你的控制器动作中使用它。

var dataFromRepo = 
routerrepository.GetRouterStatusByMac("f8:b5:68:a0:10:1c");
var routerStatusViewModel = new RouterStatusViewModel{
    //object initializer
    WANIPAddress = dataFromRepo.WANIPAddress,
    //etc...
};
return View(routerStatusViewModel );

之后,您可以像这样访问您的数据

@model myproject.mynamespace.Models.RouterStatusViewModel

<div>@Model.WANIPAddress<div> 

或者使用html帮助器

@Html.LabelFor(x => x.WANIPAddress )
© www.soinside.com 2019 - 2024. All rights reserved.