我试图在控制器中使用它来将所有类别组合在一起并计算每个类别的总数。
//Report
public ActionResult Report()
{
var reports =
db.Product
.GroupBy(r => r.CategoryName)
.Select(r => new { Name = r.Key, Count = r.Count() });
return View(reports);
}
如何在视图中访问和显示Count和CategoryName?我想这样显示:
CategoryName Count
P1 2
P2 3
P3 4
P4 2
我在Report.cshtml中有类似的内容,但它不起作用:
@model IEnumerable<SiteKitBMI.Models.Product>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Count)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Count)
</td>
</tr>
}
</table>
任何人都能发光吗? 非常感谢任何帮助。
答案 0 :(得分:1)
您的控制器查询将一组匿名对象返回到一个视图,该视图需要一个Product
的集合,并且会抛出一个传递给字典的模型项是类型的...但是这个dictionary需要一个类型为...... 异常的模型项。
由于Product
不包含属性Count
,因此您需要创建一个视图模型来表示您要在视图中显示的内容
public class ProductQuantitiesVM
{
public string Name { get; set; }
public int Count { get; set; }
}
然后将查询投影到ProductQuantitiesVM
var reports = db.Product.GroupBy(r => r.CategoryName)
.Select(r => new ProductQuantitiesVM()
{
Name = r.Key,
Count = r.Count()
});
return View(reports);
最后,将视图更改为使用ProductQuantitiesVM
@model IEnumerable<ProductQuantitiesVM>
....