Reputation:
I'm trying to make a View which contains a list of categories. These categories have a subcategories and some subcategories also have subcategories.
In the memory I have a list of Categorie objects.
My Categorie object:
namespace modellen
{
public class Categorie
{
public int Id { get; set; }
public string Naam { get; set; }
public int HoofdCategorieId { get; set; }
}
}
My view:
@using modellen
@model List<Categorie>
@{
ViewBag.Title = "Categorieen";
}
<h2>Categorieen</h2>
<ul>
@foreach (Categorie c in Model)
{
if (c.HoofdCategorieId == 0)
{
<li>@c.Naam </li>
}
}
</ul>
If the property "HoofdCategorieId" of an object is 0, it means it is NOT a subcategory of anything. If the property "HoofdCategorieId" is 2 for example, it means that it is a subcategory of an object where the property "Id" is also 2.
I can't figure out how How would continue from here to make the subcategories appearing below each respective category.
How would I do this?
Upvotes: 1
Views: 1057
Reputation: 1
You should create a model:
public int Id {get; set;}
public string CategoryName {get; set;}
public int SubcategoryId {get; set;}
public IEnumerable<Subcategory> Subcategories {get; set;}
And second model
public int Id {get; set;}
public string SubcatecoryName {get; set;}
public int CategoryId {get; set;}
public Category Category {get; set;}
This is one to many or many to one Id are navigation properties. Then in view Foreach(var item in model) Categories From categories can take subcategories
Upvotes: 0
Reputation: 4050
@foreach (Categorie c in Model.Where(w => w.HoofdCategorieId == 0))
{
<li>@c.Naam </li>
foreach (Categorie subC in Model.Where(w => w.HoofdCategorieId == c.Id))
{
<li style="margin-left:10px;">@subC.Naam </li>
foreach (Categorie subSubC in Model.Where(w => w.HoofdCategorieId == subC.Id))
{
<li style="margin-left:20px;">@subSubC.Naam </li>
}
}
}
use Where
from linq to loop through the items you want
Upvotes: 0