jquery - 如何使用 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);
}
});
}
});
解决方案
推荐阅读
- python - models.py 类中的独特组合?
- node.js - node mongo:同时更新多个数组
- python - Django 只允许非关系和外键
- azure - 在数据工厂中对 REST API 调用进行分页
- android - Android:媒体播放器直播流在几分钟后停止超过 15 分钟大小的音频,并且不在在线流中缓冲该音频
- excel - 在 2 张纸之间查找
- java - 这个检查排列的递归函数的时间复杂度是多少?
- json - 如何从 Digital Ocean API 解析 JSON 数据
- javascript - 在我做“x=y”并改变“x”之后,它也改变了“y”。我该如何防止这种情况?
- python - 如何调用列表中的值