如何在mvc中的模型中添加多个项目

Posted

技术标签:

【中文标题】如何在mvc中的模型中添加多个项目【英文标题】:how to add multiple items in the model in the mvc 【发布时间】:2017-06-02 09:29:06 【问题描述】:

我有 2 个设备,每个设备有 10 个纬度和 10 个经度值。我有 2 个设备,每个设备都有 10 个 lat long 值,但只有 10 个项目正在添加另外 10 个设备 2 数据在模型中被替换。如何像这样在模型中添加 2 个设备数据,而不为每个设备创建 2 个不同的类。

我像这样访问视图中的模型值

 @Model[0].latitude.ToString()....@Model[9].latitude.ToString(), 
 @Model[1].longitude.ToString()....@Model[9].latitude.ToString(),

我应该能够像这样访问视图中的 2 个不同的设备数据

@Model[0][0]...[0][9];
@Model[1][0]...[1][9];

代码

  public ActionResult Index()
     
      List<AssetTrackerViewModel> model = new List<AssetTrackerViewModel>();
      model.AddRange(getAssetDetails("ED"));
      model.AddRange(getAssetDetails("EE"));
      return View(model);
     
     private List<AssetTrackerViewModel> getAssetDetails(string deviceID)
       
        List<AssetTrackerViewModel> model = new List<AssetTrackerViewModel>();

         try
          
           WebRequest req = WebRequest.Create(@"url");
           req.Method = "GET";
           req.Headers["Authorization"] = "Basic " + "a2VybmVsc3BoZXJlOmtlcm5lbHNwaGVyZQ==";
           HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
           var encoding = resp.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet);
           using (var stream = resp.GetResponseStream())
            
             var reader = new StreamReader(stream, encoding);
             var responseString = reader.ReadToEnd();

             var Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);
             var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
              .GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
              .Select(g => g.First())                                                                 .OrderByDescending(a => a.timestamp).Take(10);
              foreach (var item in items)
                
                 byte[] data = Convert.FromBase64String(item.dataFrame.ToString());
                 string hex = BitConverter.ToString(data);//converting base 64 to hexcode
                 string formattedHex = BitConverter.ToString(data).Replace(@"-", string.Empty);
                 string longitude = formattedHex.Substring(14, formattedHex.Length - 14);//04AC07EB
                 long longitudeValue = Convert.ToInt64(longitude, 16);
                 string longvalue = longitudeValue.ToString();
                 longvalue = longvalue.Insert(2, ".");
                 string latitude = formattedHex.Substring(6, formattedHex.Length - 14); //010A366B
                 long lat = Convert.ToInt64(latitude, 16);
                 string latvalue = lat.ToString();
                 latvalue = latvalue.Insert(2, ".");
                 AssetTrackerViewModel assetModel = new AssetTrackerViewModel();
                 assetModel.deviceid = deviceID;
                 assetModel.latitude = latvalue;
                 assetModel.longitude = longvalue; 
                 model.Add(assetModel);
                 
                
                 
               return model;
            

    view model

          public class AssetDetail
            
             public long id  get; set; 
             public DateTime timestamp  get; set; 
             public string dataFrame  get; set; 
            

【问题讨论】:

【参考方案1】:

修改你的类:

// this is class that represents single device
public class AssetTracker

   public AssetTracker()
   
      latitude = new List<string>();
      longitude = new List<string>();
   

   public string deviceid get; set;
   public List<string> latitude get; set;
   public List<string> longitude get; set;
   

然后你查看模型:

public class AssetTrackersViewModel

   public AssetTrackersViewModel()
   
     AssetTrackers = new List<AssetTracker>();
   

   public List<AssetTracker> AssetTrackers get;set

然后你的getAssetDetails 方法:

private AssetTracker getAssetDetails(string deviceID)

  var assetTracker = new AssetTracker  deviceid = deviceID ;

 try
  
   WebRequest req = WebRequest.Create(@"url");
   req.Method = "GET";
   req.Headers["Authorization"] = "Basic " + "a2VybmVsc3BoZXJlOmtlcm5lbHNwaGVyZQ==";
   HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
   var encoding = resp.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(resp.CharacterSet);
   using (var stream = resp.GetResponseStream())
    
     var reader = new StreamReader(stream, encoding);
     var responseString = reader.ReadToEnd();

     var Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AssetDetail>>(responseString);
     var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA="))
      .GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
      .Select(g => g.First())                                                                 .OrderByDescending(a => a.timestamp).Take(10);
      foreach (var item in items)
        
         byte[] data = Convert.FromBase64String(item.dataFrame.ToString());
         string hex = BitConverter.ToString(data);//converting base 64 to hexcode
         string formattedHex = BitConverter.ToString(data).Replace(@"-", string.Empty);
         string longitude = formattedHex.Substring(14, formattedHex.Length - 14);//04AC07EB
         long longitudeValue = Convert.ToInt64(longitude, 16);
         string longvalue = longitudeValue.ToString();
         longvalue = longvalue.Insert(2, ".");
         string latitude = formattedHex.Substring(6, formattedHex.Length - 14); //010A366B
         long lat = Convert.ToInt64(latitude, 16);
         string latvalue = lat.ToString();
         latvalue = latvalue.Insert(2, ".");

         assetTracker.latitude.Add(latvalue);
         assetTracker.longitude.Add(longvalue);
         

         return assetTracker;
        
         
    

然后:

 public ActionResult Index()
 
  var model = new AssetTrackersViewModel();
  model.AssetTrackers.Add(getAssetDetails("ED"));
  model.AssetTrackers.Add(getAssetDetails("EE"));
  return View(model);
 

然后,你可以调用 Razor:

@model AssetTrackersViewModel

对于第一个“设备”

 @Model.AssetTrackers[0].latitude[0]
 @Model.AssetTrackers[0].longitude[0]

 @Model.AssetTrackers[0].latitude[9]
 @Model.AssetTrackers[0].longitude[9]

第二个“设备”

 @Model.AssetTrackers[1].latitude[0]
 @Model.AssetTrackers[1].longitude[0]

 @Model.AssetTrackers[1].latitude[9]
 @Model.AssetTrackers[1].longitude[9]

【讨论】:

由于视图模型的名称和返回类型不正确而出现一些错误。你能检查一下 once.somewhere AssetTrackersViewModel 和 some where AssetTrackerViewModel 抱歉写它记事本 :) 你到底在哪里得到错误? 您的剃刀视图必须在顶部声明@model AssetTrackersViewModel 我已经这样声明了“@model smartpond.Models.AssetTrackersViewModel”。错误 - 不可调用的成员“AssetTrackersViewModel”不能像方法一样使用。行 - var model = AssetTrackersViewModel(); deviceid 不是一个数组——它只是一个字符串字段,所以称它为:@Model.AssetTrackers[0].deviceidlatitudelongitude 是数组,deviceid 不是

以上是关于如何在mvc中的模型中添加多个项目的主要内容,如果未能解决你的问题,请参考以下文章

单个解决方案中的多个 MVC 项目

ASP.net MVC - 如何在各种视图中保留模型

如何在 ASP.NET MVC 中使用多个表单元素

MVC如何正确添加业务层

如何在没有循环或jquery的mvc中使用模型类添加动态控件

在 MVC/Razor 中,如何获取多个复选框的值并将它们全部传递给控制器​​?