How to create dynamic menu using tree

前端 未结 1 1705

I have an Angular project but this is not directly related to Angular and I just need the logic of create dynamic menu using tree that can also be similar as in ASP.NET MVC

1条回答
  •  伪装坚强ぢ
    2020-12-04 02:00

    Your database Menu table is fine to generate the treeview using the PrimeNG Tree plugin except that you may want to include an additional property for the data property if you want. I would however suggest you make the ParentId property nullable so that your top level item (Documents) has a null value rather that 0.

    In order to pass json in that format, your model need to be

    public class MenuVM
    {
        public int Id { get; set; } // this is only used for grouping
        public string label { get; set; }
        public string expandedIcon { get; set; }
        public string collapsedIcon { get; set; }
        public string icon { get; set; }
        public IEnumerable children { get; set; }
    }
    

    You might also include other properties such as

    public string data { get; set; }
    

    to match the properties in the api

    You also need a parent model for the data property

    public class TreeVM
    {
        public IEnumerable data { get; set; }
    }
    

    To generate the model, you controller code would be (note this is based on the ParentId field being null for the top level item as noted above)

    // Sort and group the menu items
    var groups = db.Menus
        .OrderBy(x => x.ParentId).ThenBy(x => x.Order)
        .ToLookup(x => x.ParentId, x => new MenuVM
        {
            Id = x.Id,
            label = x.Name
        });
    // Assign children
    foreach (var item in groups.SelectMany(x => x))
    {
        item.children = groups[item.Id].ToList();
        if (item.children.Any())
        {
            .... // apply some logic if there a child items, for example setting 
                 // the expandedIcon and collapsedIcon properties
        }
        else
        {
            .... // apply some logic if there are no child items, for example setting 
                 // the icon properties - e.g. item.icon = "fa-file-word-o";
        }
    }
    // Initialize model to be passed to the view
    TreeVM model = new TreeVM
    {
        data = groups[null].ToList();
    }
    return Json(model, JsonRequestBehavior.AllowGet);
    

    For your icons, you should consider some const values or an enum rather than hard-coding strings.

    0 讨论(0)
提交回复
热议问题