使用web api的asp.net核心razor页面中的mysql端菜单

laawzig2  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(521)

谁能给我一个在asp.NETCore中做侧菜单的例子?我下面有一个例子,但我不知道如何使用它。

[
  {
    "MenuName": "Hirer HP Transactions",
    "MenuList": [
      {
        "MenuName": "HP Application Master",
        "MenuList": []
      },
      {
        "MenuName": "HP Hirer Master",
        "MenuList": []
      },
      {
        "MenuName": "HP Collection",
        "MenuList": []
      },
      {
        "MenuName": "Post Dated Cheque",
        "MenuList": []
      },
      {
        "MenuName": "Operation Reports",
        "MenuList": []
      }
    ]
  },
  {
    "MenuName": "Vehicle Trading Transactions",
    "MenuList": [
      {
        "MenuName": "Purchase Agreement",
        "MenuList": [
          {
            "MenuName": "Open Vehicle Module",
            "MenuList": []
          },
          {
            "MenuName": "Open / Unsold Vehicles",
            "MenuList": []
          },
          {
            "MenuName": "Import Vehicle Delivery Monitoring",
            "MenuList": []
          }
        ]
      },
      {
        "MenuName": "Sales Order",
        "MenuList": []
      },
      {
        "MenuName": "Sales Agreement",
        "MenuList": []
      },
      {
        "MenuName": "Stock Master",
        "MenuList": []
      },
      {
        "MenuName": "Operation Reports",
        "MenuList": []
      }
    ]
  }
]
oxiaedzo

oxiaedzo1#

简短回答:
查询数据库并获取菜单数据
将菜单呈现为html。
既然您已经有了菜单数据,我将向您展示如何用大约40行javascript代码来呈现它:
首先,创建一个 Sidebar.lib.js 有助于将菜单呈现为html:

function SideBar(menus=[],onclick){
    this.menus=menus;
    this.onclick= onclick;
}

SideBar.prototype.render = function(){
    return `<ul class="nav bd-sidenav">${this.menus.map(m=> this._renderListItem(m)).join("")}</ul>`;
}

SideBar.prototype.attach=function(elementContainer = new HTMLElement()){
    var innerHtml = this.render();
    elementContainer.innerHTML= innerHtml;
    elementContainer.onclick = (e)=>{
        e.preventDefault();
        e.stopPropagation();
        if(e.srcElement.tagName.toLowerCase()=="a"){
            if(this.onclick != null) this.onclick(e.target);
        }
        return false;
    };
}

SideBar.prototype._renderListItem = function(li){
    if(Array.isArray(li.MenuList) && li.MenuList.length >0 ){
        return `<li>
            <a href="#${li.MenuName}">${li.MenuName}</a>
            <ul> ${li.MenuList.map(item=> this._renderListItem(item)).join(" ")} </ul>
        </li>`;
    }
    return `<li><a href="#${li.MenuName}" >${li.MenuName}</a></li>`;
}

现在可以动态创建侧边栏:

var x = new SideBar(menus);
// add your own onclick as you like 
x.onclick = t=>{
    console.log(`clicked!`,t);
};
x.attach(document.querySelector("nav.collapse"));

相关问题