How to creating a Dynamic sub-menus by sub-categories

后端 未结 1 1507
北荒
北荒 2021-01-28 08:21

I\'m setting a Menu with Sub-menu display Sub-categories, in database I created a column isSelected with Boolean data type. If only

1条回答
  •  日久生厌
    2021-01-28 08:41

    Check if this helps.

    public abstract class BaseController : Controller
    {
    
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IEnumerable menus = BuildMenu();
            ViewBag.Menus = menus;
            //base.OnActionExecuting(filterContext);
        }
    
        private IEnumerable BuildMenu()
        {
            IEnumerable menus = new List
            {
                new MVC3Stack.Models.MenuItem{Id = 1, Level = 0, ParentId = 0, Text = "Main", Url = Url.Action("Index", "Home"), IsSelected=true, HasChildren=true },
                new MVC3Stack.Models.MenuItem { Id = 2, Level = 1, ParentId = 1, Text = "Main-SubMenu1", Url = Url.Action("Index", "Home"), IsSelected=false, HasChildren=false },
                new MVC3Stack.Models.MenuItem { Id = 3, Level = 1, ParentId = 1, Text = "Main-SubMenu2", Url = Url.Action("Index", "Home"), IsSelected=true , HasChildren=false},
                new MVC3Stack.Models.MenuItem { Id = 4, Level = 0, ParentId = 0, Text = "Second Menu", Url = Url.Action("Index", "Home") ,IsSelected=true, HasChildren=true},
                new MVC3Stack.Models.MenuItem { Id = 5, Level = 1, ParentId = 4, Text = "Second Menu-SubMenu1", Url = Url.Action("Index", "Home"),IsSelected=true, HasChildren=false }
            };
            return menus;
        }
    }
    

    Here is the _layout.cshtml

    @{
      var topLevel = ((IEnumerable)ViewBag.Menus).Where(x => x.Level == 0);
     }
     
    

    This can give you some pointers on how to implemente this. Note: Number of levels will be fixed with this solution.

    0 讨论(0)
提交回复
热议问题