Answer the question
In order to leave comments, you need to log in
How to correctly present a dynamic menu stored in the database in ASP.NET MVC?
Good afternoon, @User.Name Please tell me
how to display the menu stored in the database in _MainLayout.
It is not possible to pass the model in each controller.
I decided to do it directly through the helper:
public class Menu
{
public static IEnumerable<Category> Categories
{
get
{
using (ModelContext db = new ModelContext())
return db.Categories;
}
}
}
@foreach (var item in Menu.Categories)
{
<li>@Html.ActionLink(item.Title, "Index", "Catalog", new { category = item.Alias }, null)</li>
}
Answer the question
In order to leave comments, you need to log in
I would advise you to use MvcSiteMapProvider, you will need to write an owl DynamicNodeProvider. MvcSiteMapProvider solves most menu, sitemap, and breadcrumb problems.
Use the helper in Razor -
@helper RenderMenu(IEnumerable<Menu> items)
{
foreach(var item in items)
{
<li><a href='@item.Url'>@item.Title</a></li>
@if(item.Childs.Any())
{
@RenderMenu(item.Childs)
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question