I am beginner programmer. I am trying to display hierarchy but one nested child menu is not showing. I guess there is an error in my logic but not being able to find. Anyone mind to point out the area for which one child menu called child 4 is not showing in UI.
Here is code
public ActionResult Index()
{
List<MenuItem> mi = new List<MenuItem>
{
new MenuItem {Id=1,Name="Parent 1", ParentId=0},
new MenuItem {Id=2,Name="child 1", ParentId=1},
new MenuItem {Id=3,Name="child 2", ParentId=1},
new MenuItem {Id=4,Name="child 3", ParentId=1},
new MenuItem {Id=5,Name="Parent 2", ParentId=0},
new MenuItem {Id=6,Name="child 4", ParentId=4}
};
ViewBag.menusList = mi;
return View();
}
public class MenuItem
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
}
Razor code
@{ var menusList = ViewBag.menusList as List<Scaffolding.Controllers.MenuItem>; }
@if (menusList != null)
{
<ul id="menu">
@foreach(var parentMenu in menusList.Where(p => p.ParentId == 0))
{
<li>
<span>@parentMenu.Name</span>
@if (menusList.Count(p => p.ParentId == parentMenu.Id) > 0)
{
<ul id="menu">
@foreach(var childMenu in menusList.Where(p => p.ParentId == parentMenu.Id))
{
<li>
<span>@childMenu.Name</span>
</li>
}
</ul>
}
</li>
}
</ul>
}
thanks in advance.
EDIT
i have changed the code and now getting error called
CS1502: The best overloaded method match for 'ASP._Page_Views_Menu_Index_cshtml.ShowTree(System.Collections.Generic.List)' has some invalid arguments
still my code is not working. here is updated code
razor code
@{
var menuList = ViewBag.menusList as List<Scaffolding.Controllers.MenuDTO>;
ShowTree(menuList);
}
@helper ShowTree(List<Scaffolding.Controllers.MenuDTO> menusList)
{
if (menusList != null)
{
foreach (var item in menusList)
{
<li>
<span>@item.Name</span>
@if (item.Children.Any())
{
<ul>
@ShowTree(item.Children)
</ul>
}
</li>
}
}
}
Action code
public ActionResult Index()
{
List<MenuItem> allMenu = new List<MenuItem>
{
new MenuItem {Id=1,Name="Parent 1", ParentId=0},
new MenuItem {Id=2,Name="child 1", ParentId=1},
new MenuItem {Id=3,Name="child 2", ParentId=1},
new MenuItem {Id=4,Name="child 3", ParentId=1},
new MenuItem {Id=5,Name="Parent 2", ParentId=0},
new MenuItem {Id=6,Name="child 4", ParentId=4}
};
List<MenuDTO> mi = allMenu
.Select(e => new
{
Id = e.Id,
Name = e.Name,
ParentId = e.ParentId,
Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
}).ToList()
.Select(p => new MenuDTO
{
Id = p.Id,
Name = p.Name,
ParentId = p.ParentId,
Children = allMenu.Where(x => x.ParentId == p.Id).ToList()
}).ToList();
ViewBag.menusList = mi;
return View();
}
Class code
public class MenuItem
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public virtual ICollection<MenuItem> Children { get; set; }
}
public class MenuDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public virtual ICollection<MenuItem> Children { get; set; }
}