I’m trying to learn MVC and finding a few roadblocks.
I’m trying to find a maintainable way of presenting a list of items divided by category headers. For example:
Entre
Soup
BreadMain
Chicken
Beef
VegetarianDesert
Cake
Ice cream
The category and the item are separate models, with the item model holding the category’s ID.
I want to give these pages to someone who is familiar with HTML but not ASP. For this reason, I want to keep the code embedded in the page to a minimum. This is the best I have so far, but I’m not happy with having to use and check against a variable for each item.
@{string categoryName = null;}
@foreach (var item in Model) {
if (item.CategoryName != categoryName)
{
categoryName = item.CategoryName;
<tr>
<td colspan="5">@Html.DisplayFor(modelItem => categoryName)</td>
</tr>
}
<tr><!-- Display item here --></tr>
}
Is there a method of nesting pages, such that I could make a parent page that loops through each category and calls a child page that loops through the items in that category? For example, something like:
@foreach (var item in Model) {
<tr>
<td colspan="5">@Html.DisplayFor(modelItem => item.Name)</td>
</tr>
@RenderChildren(item.Children);
}
I suggest returning a view model that has the items pre-grouped using
GroupBy:This view can iterate over the groups, display the header for each (
Key) and send the items collection to a partial view:Then the separate partial view “Meals.cshtml” accepts an
IEnumerableof your model type as its model.