2013-11-26 11 views
0

这里是我的问题: 我有一个数据库,我有一个表设备有一些设备,并且每个设备都有一个类型。 我想查看一下在表格中每种类型的设备数量。 什么我到现在就是在控制器:计算一个类型的多少个元素并返回一个视图MVC C#

public ActionResult Stock() 
{ 
    var device = db.Device.Where(s => s.Status.ToUpper().Contains("Stock")).GroupBy(d => d.DeviceTypeName); 
    return View(device.ToList()); 
} 

在视图中我有:

@model IEnumerable<System.Linq.IGrouping<System.String, Mobile_Inventory.Models.Device>> 

<table> 
    <tr> 
     <th> 
     DeviceType 
     </th> 
     <th> 
      Qt 
     </th> 

@foreach (var item in Model) { 

    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Key) 
     </td> 
    <td> 

    </td> 


</tr> 
} 

</table> 

不过这样一来,我只可以看到设备的类型,而不是数量。

我试图改变VAR设备具有数量:

var device = db.Device.Where(s => s.Status.ToUpper().Contains("Stock")).GroupBy(d => d.DeviceTypeName).Select(d => new 
    { 
     Type = d.Key, 
     Count = d.Count() 
    }); 

但这种方式我返回一个匿名类型的视图,并出现错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[<>f__AnonymousType2 2[System.String,System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[System.Linq.IGrouping 2[System.String,Mobile_Inventory.Models.Device]]'.

不知道我如何改变视图的模型类型接受匿名类型,并不知道它是否可能。任何人都可以通过解决方案提供帮助

+0

使用Tuple?而不是匿名类型,只需使用Tuple ? – Vivek

回答

1

创建一个视图模型是这样的:

public class DeviceGroupViewModel 
{ 
    public string Type { get; set; } 
    public int Count { get; set; } 
} 

然后,改变你的行动是:

public ActionResult Stock() 
{ 
    var devices = db.Device.Where(s => s.Status.ToUpper().Contains("Stock")) 
      .GroupBy(d => d.DeviceTypeName) 
      .Select(d => new DeviceGroupViewModel 
      { 
       Type = d.Key, 
       Count = d.Count() 
      }).ToList(); 

    return View(devices); 
} 

而且,在你看来,你必须:

@model IEnumerable<Mobile_Inventory.ViewModels.DeviceGroupViewModel> 

<table> 
    <tr> 
     <th> 
     DeviceType 
     </th> 
     <th> 
      Qt 
     </th> 
    </tr> 
@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(item => item.Type) 
     </td> 
     <td> 
      @Html.DisplayFor(item => item.Count) 
     </td> 
    </tr> 
} 

+0

很简单,Tks!有效! – user2962069

+0

不客气。然后,选择它作为正确的答案,所以其他人知道这个问题已被回答。 – ataravati

相关问题