Dynamic Menu loading in ASP.Net MVC3 Razor

后端 未结 1 1149
梦如初夏
梦如初夏 2021-02-11 06:03

I want to ask about Dynamic Database Driven Menu Loading in ASP.Net

MVC3 razor .

This is my

1.View Code

2.Model for Menu

3.Model For

相关标签:
1条回答
  • 2021-02-11 07:00

    Put below div in _Shared.cshtml

      <nav id="mainNavigation">
                @Html.Partial("_MenuLayout")
       </nav>
    

    Make new _MenuLayout.cshtml view for dynamic generated menu

    In your controller , write code to get Data from database table e.g. MenuTable and prepare list and assign values like below

      ViewBag.Menu = list;
    

    and in your _MenuLayout.cshtml partial view place below code,

    @{ var menusList = ViewBag.Menu as IEnumerable<Elixir.Models.MenuItem>; }
    
     @if (menusList != null)
    {
       <ul id="menu" class="wrap cf">
        @foreach (var parentMenu in menusList.Where(p => p.ParentMenuID == 0))
        {
            <li>
                @if (!string.IsNullOrEmpty(@parentMenu.ActionName))
                {
                     @Html.ActionLink(@parentMenu.MenuName, @parentMenu.ActionName, @parentMenu.ControllerName)
                }
               else
               {
                  <span>@parentMenu.MenuName</span> 
                    if (menusList.Count(p => p.ParentMenuID == parentMenu.MenuID) > 0)
                    {
                        <ul>
                            @foreach (var childMenu in menusList.Where(p => p.ParentMenuID == parentMenu.MenuID))
                            { 
                                 <li>@Html.ActionLink(@childMenu.MenuName, @childMenu.ActionName, @childMenu.ControllerName)</li>
    
                                if (menusList.Count(p => p.ParentMenuID == childMenu.MenuID) > 0)
                                {
                                    foreach (var subChild in menusList.Where(p => p.ParentMenuID == childMenu.MenuID))
                                    {
                                @Html.ActionLink(@subChild.MenuName, @subChild.ActionName, @subChild.ControllerName)
                                    }
                                }
                            }
                        </ul>
                    }        
               }
    
            </li>
        }
     </ul>
    }
    
    0 讨论(0)
提交回复
热议问题