Reputation: 253
I'm still learning .net MVC, and perhaps am not searching correctly for what I need to find a solution to.
In short, I have a table in the database that is structured as:
ID Category Subcategory FK
So each category may appear multiple times, as well as each subcategory, which is unique to the category.
I want to render a menu in the view that looks like:
Category 1
Subcategory 1a
Subcategory 1b
Subcategory 1c
Category 2
Subcategory 2a
Subcategory 2b
And so on. Right now in the controller I have:
var categories = db.Category
.Where(oa => oa.Category != "")
.GroupBy(oa => new { oa.Category, oa.Subcategory })
.Select(oa => oa.FirstOrDefault());
However, I'm not sure how to do what I want to achieve in the view. I know I have to loop through the list somehow, but I'm not sure how. I know it involved something along the lines of:
@foreach (var item in Model)
{
<li>
<a id="@item.ID" href="#">@item.Category</a>
</li>
}
But I only want each category to appear once, and then need all subcategories to appear under the parent category. Or maybe I need to change the controller and how it sends the data?
Upvotes: 2
Views: 2000
Reputation:
Start by creating a simple view model to represent what you want to display in the view
public class CategoryVM
{
public string Name { get; set; }
public IEnumerable<string> SubCategories { get; set; }
}
Then project your query to a collection of that view model and return it to the view
var model = db.Category.Where(x => x.Category != "")
.GroupBy(x => x.Category).Select(x => new CategoryVM
{
Name = x.Key,
SubCategories = x.Select(y => y.Subcategory)
});
return View(model);
and in the view
@model IEnumerable<CategoryVM>
....
@foreach(var category in Model)
{
<h2>@category.Name</h2>
<ul>
@foreach(var subCategory in category.SubCategories)
{
<li>@subCategory</li>
}
</ul>
}
Upvotes: 5