Reputation: 1105
I'm working on a ASP.NET MVC3 web application and I want to create a navigation menu that has a sub menu created dynamically from an object. For example I have a Library object/model that contains a list of Books. I want my Navigation to dynamically populate a link to each of those books and display their titles.
Ex:
Home
Book List
- Book 1
- Book 2
- Book 3
About
I have this working by passing the Library object through ViewData from my Controller. My shared _Layout.cshtml page then reads the ViewData and populates the navigation menu. However the downside to this solution is that every method that returns a view in my controllers has to place the Library object into the ViewData. So I'm wondering if there is a better or simpler way to do this?
I'm sure it can be done with jQuery, but maybe you all have a better idea.
Upvotes: 3
Views: 1453
Reputation: 1105
The link Erik posted to Phil Haack's blog is the right solution, but it took me a while to figure out what Phil's example was doing. It's a pretty old MVC2 example so here is an example of what my program ended up looking like in case someone has the same question.
Home Controller:
[ChildActionOnly]
public ActionResult Menu()
{
Library library = something.getLibrary();
return PartialView("_MenuPartial", library);
}
Shared Partial View _MenuPartial.cshtml:
@model ProjectName.Models.Library
<ul>
@foreach (var book in @Model.BookList)
{
<li><a href="#">@book.Title</a></li>
}
</ul>
Shared View _Layout.cshtml:
<html>
<head>
</head>
<body>
<nav>
@{Html.RenderAction("Menu","Home");}
</nav>
</body>
</html>
Upvotes: 0
Reputation: 54656
Take a look at Phil Haacked blog Html.RenderAction and Html.Action. His example is actually a menu that you could easily call from a layout.
Upvotes: 3