如何建立動態選單在ASP。 淨核心剃刀頁面與Web Api
我得到一個錯誤當我新增一個MenuList進入選單。 電腦科學,因為我的MySql表中沒有MenuList那裡。 但我無法新增MenuList選單。 cs,這意味著我不能建立一個動態選單,任何人在這種情況下有解決方案嗎? 請幫助我,我被困在這裡大約一個星期。
MySql表:
CREATE TABLE Menusss(
MenuId int not null auto_increment,
MenuName varchar(250),
ParentId int,
ActiveNo int
);
Menus.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>();
}
MenusController.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();
}
MY.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); } }); }
});