首页 > 解决方案 > 如何使用 Web Api 在 ASP.NET Core Razor 页面中创建动态菜单

问题描述

当我将 MenuList 添加到 Menus.cs 时出现错误,因为在我的 MySql 表中没有 MenuList。但是我无法在 Menus.cs 中添加 MenuList,这意味着我无法正确创建动态菜单,有人对此案有解决方案吗?请帮助我,我被困在这里大约一个星期。

MySql 表:

CREATE TABLE Menusss(
    MenuId int not null auto_increment,
    MenuName varchar(250),
    ParentId int,
    ActiveNo int
);

菜单.cs:

public class Menus
{
    [Key]
    public int MenuId { get; set; }
    public string MenuName { get; set; }
    public int? ParentId { get; set; }
    public int ActiveNo { get; set; }
    public List<Menus> MenuList { get; set; } = new List<Menus>();
}

菜单控制器.cs:

[HttpGet]
public ActionResult<List<Menus>> GetMenus()
{
    List<Menus> menuList = new List<Menus>();

    foreach (Menus m in _context.menus.ToList())
    {
        menuList.Add(m);
    }

    List<Menus> menuTree = GetMenuTree(menuList, null);
    return menuTree;
}

private List<Menus> GetMenuTree(List<Menus> list, int? parentId)
{
    return list.Where(x => x.ParentId == parentId).Select(x => new Menus()
    {
        MenuId = x.MenuId,
        MenuName = x.MenuName,
        ParentId = x.ParentId,
        ActiveNo = x.ActiveNo,
        MenuList = GetMenuTree(list, x.MenuId)
    }).ToList();
}

我的.js:

$(document).ready(function () {
    $.ajax({
        url: '',
        method: 'get',
        dataType: 'json',
        success: function (data) {  
        buildMenu($('#menu'), data);
        $('#menu').menu();
    }
});

    function buildMenu(parent, items) {
        $.each(items, function () {
            var li = $("<li>" + this.MenuName + "</li>");
            if (this.ActiveNo == 0) {
                li.addClass('ui-state-disabled');
            }

            li.appendTo(parent);

            if (this.MenuList && this.MenuList.length > 0) {
                var ul = $("<ul></ul>");
                ul.appentTo(li);
                buildMenu(ul, this.MenuList);
            }
        });
    }
});

标签: jquerymysqlasp.netasp.net-coremenu

解决方案


推荐阅读