Search code examples
asp.net-mvcasp.net-mvc-5submenu

ASP.NET MVC5 dynamic submenu with links generated from DB


I need to have a submenu(Executive Sections) for a section called 'Executives'. This menu must show up when a user clicks Executives in the main menu and remain as long as any submenu link of Executives is clicked. Catch is: the submenu links are dynamic and come from the DB/CMS system, so it's not a hard-coded list. Which is where my woe begins. Currently, I have it in a PartialView that requires a model of IEnumerable so it can build dynamically. But how I go about making this work as I need it too is a little twisted up in my mind.

@using xxx.Models
@model IEnumerable<xxx.Models.ExecutiveSection>
<ul class="nav navbar-nav">
@foreach (ExecutiveSection es in Model)
{
    <li>@Html.ActionLink(es.SectionName, "Section", "Executive", new { id = es.ExecutiveSectionId })</li>
}


Solution

  • I solved it. Did this in the _Layout

     @{ // Sub-Menu for Executive Sections
                if (HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString().Contains("Executive"))
                {
                    Html.RenderAction("ExecutiveSubMenu", "Executive");
                }
            }   
    

    And in the controller:

    public ActionResult ExecutiveSubMenu()
        {
            // get sections
            var sections = db.ExecutiveSections.ToList();
            return PartialView("ExecutiveSubMenuView", sections);
        }
    

    and finally the Partial:

    @using xxx.Models
    @model IEnumerable<xxx.Models.ExecutiveSection>
    <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        @foreach (ExecutiveSection es in Model)
        {
            <li>@Html.ActionLink(es.SectionName, "Section", "Executive", new { id = es.SectionName.Replace(" ", "-") }, null)</li>
        }
    </ul>
    

    (I 'replace' the spaces in any section name with dashes '-' and back again for SEO friendliness.)