ASP.Net MVC: How to show nested parent-child relation using recursive technique

后端 未结 2 799
天命终不由人
天命终不由人 2020-12-20 04:36

I am just trying to display nth relation using ul and li in razor using recursive function call. Suppose I have db table where I store parent child

2条回答
  •  生来不讨喜
    2020-12-20 04:39

    Your code is not able to find a function ShowTree taking a parameter of type ICollection when it executes the line

    @ShowTree(item.Children)
    

    because item.Children is of type ICollection. The function ShowTree in your code takes a parameter of a different type, List, which is not the same as ICollection. As a result, the runtime reports the CS1502 error you see.

    After realizing that you were looking for a recursive solution, I have modified the code to do just that.

    Action Code

    public ActionResult Index()
    {
    
        List allMenu = new List
        {
            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 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 = GetChildren(allMenu, e.Id) /* Recursively grab the children */
        }).ToList();
    
        ViewBag.menusList = mi;
    
        return View();
    }
    
    /// 
    /// Recursively grabs the children from the list of items for the provided parentId
    /// 
    /// List of all items
    /// Id of parent item
    /// List of children of parentId
    private static List GetChildren(List items, int parentId)
    {
        return items
            .Where(x => x.ParentId == parentId)
            .Select(e => new MenuItem
            {
                Id = e.Id,
                Name = e.Name,
                ParentId = e.ParentId,
                Children = GetChildren(items, e.Id)
            }).ToList();
    }
    

    Razor Code

    @{
        var menuList = ViewBag.menusList as List;
        @ShowTree(menuList);
    }
    
    @helper ShowTree(List menusList)
    {
        if (menusList != null)
        {
            foreach (var item in menusList)
            {
                
  • @item.Name @if (item.Children.Any()) {
      @ShowTree(item.Children)
    }
  • } } }

提交回复
热议问题