【问题标题】:Blazor Page - Recursive menuBlazor 页面 - 递归菜单
【发布时间】:2021-10-08 15:21:10
【问题描述】:

我正在构建一个 Blazor 页面(作为一个学习项目)并希望创建一个基于用户权限的动态菜单。

我的表格布局是

MenuItemID | ItemName | ParentID

我想从这个表中加载信息并动态创建菜单。我正在使用 MudBlazor 进行菜单布局。

在标准 Winforms 中,我很熟悉如何递归调用函数,但我不确定如何在 Blazor 中执行此操作以动态生成 HTML。

我编写了一个用于查找项目的函数

private List<MenuItem> GetChildItems(int ParentID)
{
    var foundItems = from m in menuItems
                     where m.ParentID == ParentID
                     select m;

    return foundItems.ToList();
}

我的想法是我的页面中的代码会以这样的开头:

@if (menuItems == null)
{
    <div class="spinner"></div>

}
else
{
    foreach (MenuItem p in GetChildItems(0))
    {
        List<MenuItem>
            children = GetChildItems(p.MenuItemID);
        if (children.Count > 0)
        {
            <MudNavGroup Title="@p.ItemName" Icon="@Icons.Material.Outlined.AssignmentInd" HideExpandIcon="true">
                @foreach (MenuItem c in children)
                {
                    <MudNavLink Href="pages/authentication/login" Icon="@Icons.Material.Outlined.InsertDriveFile">@c.ItemName</MudNavLink>
                }
            </MudNavGroup>
        }
        else
        {
            <MudNavLink Href="/FetchData" Match="NavLinkMatch.All" Icon="@Icons.Material.Outlined.Dashboard">@p.ItemName</MudNavLink>
        }
    }
}

我不能 100% 确定如何将其转换为递归搜索?

谢谢 斯蒂芬

【问题讨论】:

    标签: blazor


    【解决方案1】:
    public class MenuItems 
    {
      public int Id {get; set;} 
      public int? ParentId {get; set;}
      public string Title {get; set;}
      public bool IsOpened {get; se;}
    }
    //Your data will look like this, but you can extend the class up to have Icon property and StyleCss.
    var itemList= new List<MenuItems> 
         {
            new MenuItems = (Id=1, Title="fruits", ParentId= null},
            new MenuItems = (Id=2, Title="apple", ParentId= 1},
            new MenuItems = (Id=3, Title="banana", ParentId= 1}
            new MenuItems = (Id=4, Title="mango", ParentId= 1}
            new MenuItems = (Id=5, Title="vegetables", ParentId= null}
            new MenuItems = (Id=6, Title="pepper", ParentId= 6}
            new MenuItems = (Id=7, Title="carrot", ParentId= 6}
        };
    

    在 blazor 页面中,递归应该是这样的:

    @foreach(var item in itemList.Where(i => i.ParentId == ParentId))
    {
      <li style="cursor:pointer" @onclick="() => item.IsOpened = !item.IsOpened">
          @item.Name
          @if (item.IsOpened && itemList.Where(c => c.ParentId == item.Id).Any())
            {
              <ul>
               <RecursiveUI ParentId="item.Id" />
            </ul>
            }
      </li>
    

    问题已回答Here

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2013-11-05
      • 2013-06-13
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多