V
V
Viktor Korzunin2015-05-29 12:36:19
ASP.NET
Viktor Korzunin, 2015-05-29 12:36:19

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;
            }
        }
    }

_MainLayout view:
@foreach (var item in Menu.Categories)
                    {
                        <li>@Html.ActionLink(item.Title, "Index", "Catalog", new { category = item.Alias }, null)</li>
                    }

But I doubt it's the right thing to do. Any advice for a newbie?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-05-29
@senal

I would advise you to use MvcSiteMapProvider, you will need to write an owl DynamicNodeProvider. MvcSiteMapProvider solves most menu, sitemap, and breadcrumb problems.

A
Artur Nurullin, 2015-06-15
@Splo1ter

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)
          }
    }
}

Well, the whole thing is recursively displayed in html.
And rename the class - you have it like menu but returns categories, maybe it's better to just transfer this method to the category?
Or is it generally better to make a separate controller with a child ActionResult in which to issue only a menu.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question