I'm trying to use this in the controller to get group all Category together and Count the total of each Category.
//Report
public ActionResult Report()
{
var reports =
db.Product
.GroupBy(r => r.CategoryName)
.Select(r => new { Name = r.Key, Count = r.Count() });
return View(reports);
}
How to access and display the Count and CategoryName in the View? I want to display it like this:
CategoryName Count
P1 2
P2 3
P3 4
P4 2
I have something like this in the Report.cshtml but it's not working:
@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>
Can anyone shine some light onto this?? Any help is much appreciated.
IEnumerable<Product>to the view (your code would be throwing an exception). Create a view model (sayProductVM)containing propertiesNameandCountand project your query into it, -select r => new ProductVM { ... }and then it to a view with@model IEnumerable<ProductVM>