The HTML menu rendered from my helper function is
-
Category 1
- Category 2
- Category 2
- Category 3
- Category 4
I have set Category 2 as a child category of Category 1.
Unfortunately, the current HTML helper displays again Category 2 as a parent afterwards.
Id ParentCategoryId Description
1 NULL Category 1
2 1 Category 2
3 NULL Category 3
4 NULL Category 4
5 NULL Category 5
How should I modify my helper function?
@{ Func<dynamic, IHtmlContent> ShowMenu(List<Category> cats) =>
@<ul>
@foreach (var cat in cats)
{
<li>
@cat.Description
@if (cat.Childs != null && cat.Childs.Any())
{
@ShowMenu(cat.Childs)(null)
}
</li>
}
</ul>;
}
The category model used is as
public class Category
{
public int Id { get; set; }
public int? ParentCategoryId { get; set; }
public Category ParentCategory { get; set; }
[ForeignKey("ParentCategoryId")]
public List<Category> Childs { get; set; }
public string Description { get; set; }
}
The html menu is displayed in razor via
@ShowMenu(Model.Categories)(null)
where
Model.Categories = context.Categories.ToList()
Update: Thanks to the helpfull answers given, it seems i should also pass the parent category as a parameter.
@{ Func<dynamic, IHtmlContent> ShowMenu(List<Category> cats, Category parent) =>
@<ul>
@foreach (var cat in cats)
{
<li>
@cat.Description
@if (cat.Childs != null && cat.Childs.Any())
{
@ShowMenu(cat.Childs, cat)(null)
}
</li>
}
</ul>; }
ParentCategoryId == nullto yourShowMenu.And the categories need to contain all the childs and childs's childs.