我正在使用菜单项的集合,每个菜单项都有一个菜单ID,父菜单ID,href链接和标签。我还定义了.Equals,如果菜单ID相等则为true。我有一个无序的列表和代码,将其填充在Page_Load中,如图所示。问题是它不适用于具有多个后代的菜单项。换句话说,孩子显示正确,但他们的孩子(孙子)显示在顶层而不是孩子的下方。我想念什么?
<ul id="menu" runat="server">
</ul>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim menuItems = GetMenuForUser()
menu.Controls.Add(CreateMenu(menu, menuItems))
End Sub
Private Function CreateMenu(parent As HtmlGenericControl, menuItems As List(Of MenuItem)) As HtmlGenericControl
For Each menuItem In menuItems
Dim item = menuItem.ToListItem
parent.Controls.Add(item)
menuItems = menuItems.Where(Function(w) Not menuItem.Equals(w)).ToList
Dim children = menuItems.Where(Function(w) w.ParentMenuId = menuItem.MenuId).toList
If children.Any Then
Dim ul = New HtmlGenericControl("ul")
item.Controls.Add(CreateMenu(ul, children))
menuItems = menuItems.Where(Function(w) Not children.Any(Function(c) c.Equals(w))).ToList
Return CreateMenu(item, menuItems)
End If
Next
Return parent
End Function
我已经定义了此帮助器功能,可以将菜单项转换为html列表项:
Public Function ToListItem() As HtmlGenericControl
Dim li = New HtmlGenericControl("li")
Dim menuLink = New HtmlAnchor
menuLink.HRef = IIf(String.IsNullOrEmpty(Me.Href), "#", Me.Href)
menuLink.InnerText = Me.Label
li.Controls.Add(menuLink)
Return li
End Function