【问题标题】:bind dynamic menu from database to a layout page and show it for all the pages of asp net core将数据库中的动态菜单绑定到布局页面,并在 asp net core 的所有页面上显示
【发布时间】:2021-01-28 05:42:22
【问题描述】:

我在 asp net core 应用程序中有一个布局页面。我想将数据库中的动态菜单绑定到它,它显示在项目的所有页面上,也有各种控制器和模型。这是我的布局页面代码:-

 @Html.Partial("_Menu", Model)

这是我的局部视图页面,名为_Menu:-

@if (ViewBag.Industries != null)
{
    @foreach (var items in ViewBag.Industries)
    {
        <li class="level0 parent drop-menu">
            <a href="index.html"><span>@items.IndustryName</span></a>
            <ul class="level1">
                @foreach (var subitems in items.MasterProductCategory)
                {
                    <li class="level1 first parent"><a href="404error.html"><span>@subitems.CategoryName</span></a></li>
                }
            </ul>
        </li>
    }
}

这是我的控制器,用于在家庭控制器中获取菜单项:-

public ActionResult _Menu()
        {
            ViewBag.Industries = _context.MasterIndustry.Include(u => u.MasterProductCategory).ToList();
            return PartialView("_Menu", ViewBag.Industries);
        }

问题是,在调试解决方案时,它正在从布局页面移动到部分页面,但它没有调用菜单控制器。结果 viewBag.Industry 为空。我必须在哪里编写菜单控制器,以便它调用菜单控制器的每个页面和每个控制器以获得所需的结果。或者如果有更好的方法来解决这个问题。请告诉我。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    需要对每个控制器上的菜单进行全局化,并强制它在任何操作之前执行。

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Your logic here...
        BindMenuItems();
        base.OnActionExecuting(filterContext);
    }
    
    public IActionResult BindMenuItems()
    {
        ViewBag.Industries = _context.MasterIndustry.Include(u => u.MasterProductCategory).ToList();
        return View();
    }
    

    布局页面:

    @if(ViewBag.Industries != null)
    {                       
        @foreach(var items in ViewBag.Industries)
        { 
            <li class="level0 parent drop-menu">
                <a href="index.html"><span>@items.IndustryName</span></a>
                <ul class="level1">                                
                    @foreach(var subitems in items.MasterProductCategory)
                    { 
                        <li class="level1 first parent"><a href="404error.html"><span>@subitems.CategoryName</span></a></li>
                    }                                  
                </ul>
            </li>
        }
    }
    

    希望这将帮助面临同样问题的其他人。我不知道它是否符合商业标准,但它可以帮助我立即获得解决方案。

    【讨论】:

      【解决方案2】:

      Partial Views 不要使用自我控制器。使用View Component 然后调用你的布局

      【讨论】:

        猜你喜欢
        • 2019-01-23
        • 2023-01-18
        • 1970-01-01
        • 2012-05-28
        • 2019-09-21
        • 1970-01-01
        • 2018-11-02
        • 2021-04-03
        • 2023-03-29
        相关资源
        最近更新 更多