ASP.Net MVC:递归方法不显示嵌套子级 [英] ASP.Net MVC: Recursive approach not showing nested child
问题描述
我正在尝试在ul/li中显示嵌套数据,但是未显示嵌套子级.查看我的代码,然后告诉我那里出了什么问题.
I am trying to show nested data in ul/li, but nested children are not showing. See my code and please tell me what is wrong there.
控制器:
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<MenuItem> mi = allMenu
.Where(e => e.ParentId == 0) /* grab only the root parent nodes */
.Select(e => new MenuItem
{
Id = e.Id,
Name = e.Name,
ParentId = e.ParentId,
Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
}).ToList();
ViewBag.menusList = mi;
return View();
}
POCO班级:
public class MenuItem
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public virtual List<MenuItem> Children { get; set; }
}
查看:
@helper ShowTree(List<Scaffolding.Controllers.MenuItem> menusList)
{
<ul>
@foreach (var item in menusList)
{
<li>
<span>@item.Name</span>
@if (item.Children != null && item.Children.Any())
{
@ShowTree(item.Children)
}
</li>
}
</ul>
}
@{
var menuList = ViewBag.menusList as List<Scaffolding.Controllers.MenuItem>;
@ShowTree(menuList);
}
如果运行代码,则将看到孩子4没有显示哪个是孩子3的孩子.请告知我需要在代码中进行哪些更改.谢谢
If you run the code then you will see child 4 is not showing which is a child of child 3. Please advise what I need to change in my code. Thanks
推荐答案
您的查询仅获取顶级元素( ParentId == 0
),然后仅填充其直接子元素.
Your query gets the top level elements (ParentId == 0
) only and then populate just their direct child elements.
您需要更改查询以填充所有级别的所有子元素.请注意,您的 MeuItem
不需要 ParentId
属性.
Your query needs to be changed to populate all child elements for all levels. Note that your MeuItem
does not need the ParentId
property.
// Group the items by parentId and project to MenuItem
var groups = allMenu.ToLookup(x => x.ParentId, x => new MenuItem
{
Id = x.Id,
Name = x.Name,
});
// Assign the child menus to all items
foreach (var item in allMenu)
{
item.children = groups[item.Id].ToList();
}
// Return just the top level items
ViewBag.menusList = groups[0].ToList();
请注意,请勿使用 ViewBag
.而是将模型传递到视图
As a side note, do not use ViewBag
. Pass the model to the view instead
return View(groups[0].ToList());
并在视图中
@model List<MenuItem>
....
@ShowTree(Model);
这篇关于ASP.Net MVC:递归方法不显示嵌套子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!