i am trying to loop through multilevel dynamic menus. I have been succeeded to do this manually i.e everytime if want to display the child Menus of it's parent, I have to loop manually. I would like to know the best way or an alternative of looping multi-level through these dynamic menus
Here is what i have done so far;
@{ var menusList = ViewBag.Menus as IEnumerable<ParentMenuViewModel>; }
@foreach (var parentMenu in menusList.Where(p => p.ParentId == 0))
{
<ul>
<li>
<h1>@parentMenu.Name</h1>
@if (menusList.Count(p => p.ParentId == parentMenu.MenuId) > 0)
{
<ul>
@foreach (var childMenu in menusList.Where(p => p.ParentId == parentMenu.MenuId))
{
<h2>@childMenu.Name</h2>
if (menusList.Count(p => p.ParentId == childMenu.MenuId) > 0)
{
foreach (var subChild in menusList.Where(p => p.ParentId == childMenu.MenuId))
{
<h3>@subChild.Name</h3>
}
}
}
</ul>
}
</li>
</ul>
}
UPDATE: The output looks like this;
HOME
SUB MENU1
SUB SUB MENU1
SUB SUB MENU2
However, i have in my database something like this;
HOME
SUB MENU1
SUB SUB MENU1
SUB SUB MENU2
Sub SUB SUB MENU1
Sub SUB SUB MENU2
Here is my model;
