I have a ViewModel:
public class Page
{
public int Id { get; set; }
public Page Parent { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
I am passing that model to a view, and i need to create a hierarchical menu based on the model:
<ul>
<li>Page
<ul>
<li>Sub Page</li>
</ul>
</li>
Through no lack of effort at all i am unable to figure out how i will be doing this recursive loop in the view.
I can create the markup in my controller, but that’s not test friendly.
Any Ideas?
there are many ways to display dynamicly generated menus and i will post my way of doing it, I have two classes Menu & MenuItem (a Menu is just a wrapper for a list of MenuItems which are the actual >”real” links) and then i have a NavigationViewModel to wrap everything.
//
// this is NavigationModel that wrap everything.
// This is an example of a method that builds a NavigationModel.
// I have a NavigationHelper that takes care of outputting the HTML with the following two methods.
Note: (this is a simplified version as in my implementation i use the id of the Menu & the MenuItem to locate the current menu that is being displayed and add the “current” CSS class to it”
finally i have a following call in my Master to display the menu.
Note: I have a strongly typed MasterPage with the type (BaseViewModel) that contains the property NavigationMenu of type NavigationModel
Connecting everything together.
In my example i have to supply my Views with a ViewModel (that inherits my BaseViewModel) at each action method to and then build the Menu (using a Builder Method that does most of the work so i don’t have to re type it in every action method). If you don’t use a BaseViewModel then you will need to find another way to build the Navigation Model and then pass the Navigation Model to your MasterPage.
For me i find having a strongly typed MasterPage to make things easier and cleaner. King wilder have a nice way of implementing them in his GolfTracker Series.