C# 计算一个视图MVC的类型和返回的元素数#
我的问题是: 我有一个数据库,其中有一个表设备,其中有一些设备,每个设备都有一个类型。 我想查看表中每种类型的设备数量。 到目前为止,我所拥有的是,在控制器中:C# 计算一个视图MVC的类型和返回的元素数#,c#,asp.net-mvc,asp.net-mvc-4,group-by,C#,Asp.net Mvc,Asp.net Mvc 4,Group By,我的问题是: 我有一个数据库,其中有一个表设备,其中有一些设备,每个设备都有一个类型。 我想查看表中每种类型的设备数量。 到目前为止,我所拥有的是,在控制器中: public ActionResult Stock() { var device = db.Device.Where(s => s.Status.ToUpper().Contains("Stock")).GroupBy(d => d.DeviceTypeName); return View(device.To
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>
但通过这种方式,我向视图返回一个匿名类型,并得到错误:
传入词典的模型项的类型为“System.Collections.Generic.List1[f_uAnonymousType2
2[System.String,System.Int32]]”,但此词典需要类型为“System.Collections.Generic.IEnumerable1[System.Linq.iGroup
2[System.String,Mobile\u Inventory.Models.Device]]的模型项
不知道如何更改视图的模型类型接受匿名类型,甚至不知道是否可能。任何人都可以提供解决方案帮助?创建如下视图模型:
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>
}
@model IEnumerable
设备类型
Qt
@foreach(模型中的var项目){
@DisplayFor(item=>item.Type)
@DisplayFor(item=>item.Count)
}
是否使用元组?不用匿名类型,只需使用元组即可?不客气。然后,选择它作为正确答案,这样其他人就知道问题已经得到了回答。
@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>
}