Creating a Dynamic Shared Dropdown Menu

To provide easy access to content directly from the menu can seem challenging especially when that content needs to be pulled from the database. Placing a dynamic menu on the shared layout however is not to hard. In this example we are going to pull a list of courses from the courses table and display them as a dropdown in the shared layout menu.

HomeController

In the HomeController we create an action titled CoursesMenu() that returns the partialview “_coursesmenu” (which we will create) and the list of courses from the database.

public ActionResult CoursesMenu()
{
     return PartialView("_coursesmenu", db.Courses.ToList());
}

_coursesmenu.cshtml Partial View

We create a partial view that takes the list of courses and loops through them to display a list of links

@model IEnumerable<ProjectName.Courses>

<ul>
    @foreach (var item in Model)
    {
        <li style="list-style-type:none">
            <a class="dropdown-item" href="@Url.Action("Lessons","Courses", new {id = @item.CourseId})">@item.CourseName</a>
        </li>
    }
</ul>

Shared Layout

Finally on the shared layout we create the dropdown list using Bootstrap and call the CoursesMenu action from the HomeController using Html.RenderAction

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Courses
    </a>

    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        @{ Html.RenderAction("CoursesMenu", "Home"); }
    </div>
</li>

Styling the menu and making it fit in with your template is simply adjusting the class styles and CSS to match you needs but this should bring in a dynamic list of courses that will be automatically updated if another course is added.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *