来自数据库的动态菜单 [英] Dynamic menu from database
问题描述
我有一个 Login page
,登录时它会将用户带到 Home Page
,其中加载了 dynamic menu
.问题是当用户点击其中一个 menulink
loaded menu
不可见
I have a Login page
where on login it takes user to Home Page
where dynamic menu
is loaded.The problem is that when a user clicks on one of the menulink
the loaded menu
is not visible
这是因为我在Home controller
的Index action
里面写了代码.
This is because I have written the code inside Index action
of theHome controller
.
所以我的问题是我应该在哪里编写动态菜单的逻辑
,以便在单击菜单链接时可以访问它.
So my question is where should I write the logic for dynamic menu
so that it is accessible on clicking the menulink.
_Layout.cshtml 加载菜单的文件
@model SMS.Models.ViewModel.DashboardVM
@if (Model != null && Model.MenuParentList.Count > 0)
{
<!-- Sidebar Menu -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="active">
<a href="#">
<i class="fa fa-dashboard"></i> <span>Dashboard</span>
</a>
</li>
@foreach (var parentItem in Model.MenuParentList)
{
<li class="treeview">
<a href="#">
<i class="fa fa-th"></i>
<span>@parentItem.MenuParentName</span>
<i class="fa fa-angle-left pull-right"></i>
</a>
<ul class="treeview-menu">
@Html.Partial("_MenuParent", Model.MenuList.Where(x => x.ParentID == parentItem.MenuParentID))
</ul>
</li>
}
</ul>
}
动态菜单的逻辑在这里
public ActionResult Index()
{
var _dashboardVM = new DashboardVM
{
User = _employee.Users.FirstOrDefault(),
MenuParentList=_db.Menus
.Where(x => _parentList.Contains(x.Id))
.Select(x => new SMS.Models.ViewModel.DashboardVM.MenuParent
{
MenuParentID = x.Id,
MenuParentName = x.MenuName
})
.OrderBy(x=>x.MenuParentID)
.ToList(),
MenuList=_employee.Designation.Role.MenuRoles
.Select(x=>x.Menu)
.ToList()
};
}
推荐答案
创建一个单独的 [ChildActionOnly]
方法来生成你的菜单并从布局页面调用它,使其在所有页面中可用>
Create a separate [ChildActionOnly]
method that generates your menu and call it from the layout page so its available in all pages
[ChildActionOnly]
public ActionResult Menu()
{
var model = new DashboardVM
{
....
}
return PartialView("_Menu", model);
}
并创建一个 _Menu.cshtml
局部视图来生成 html
and create a _Menu.cshtml
partial view to generate the html
@model DashboardVM
....
然后在您的布局中,删除 @model SMS.Models.ViewModel.DashboardVM
(布局不应有模型,除非该模型是布局使用的所有模型的基类)和然后包括
and then in your layout, remove @model SMS.Models.ViewModel.DashboardVM
(a layout should not have a model unless that model is a base class for all models used by the layout) and then include
@Html.Action("Menu", yourControllerName)
它将调用 Menu
方法并将它返回的局部视图插入到布局中.
which will call the Menu
method and insert the partial view it returns into the layout.
这篇关于来自数据库的动态菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!