ASP.NET and JQuery MVC Menu Part 1
Other posts in this series:
One of the key differences between ASP.NET Web forms and ASP.NET MVC is that WebForms contained many controls which you could use on your web pages and MVC doesn’t.
Not that this is a bad thing, the difficult thing about WebForms was the horrendous html they generated and the hoops you had to go through to gain fine control over them.
In this series of posts I will describe how to create a fully functional Menu using Html, JQuery and some C# Helper Methods.
Part 1 – Creating an MVC Menu
Creating a menu in MVC is actually pretty straightforward once you realise you’re going to have to do some of the dirty work yourself.
Start with a standard Unordered List.
Note that we have another unordered list inside the main list to create a hierarchical menu.
Now I know what you’re thinking, that’s not MVC that’s just HTML. So let’s make life easier for ourselves and introduce a helper method to render these list items for us.
Nothing fancy here, but note that we’re passing in the action and controller names. The actual work is done in the getListItem method.
This is where the fun starts (honestly!).
- First off we generate a link for the specified action and controller. This will work with whatever routing you have set up and generate a link to the action.
- We create a new TagBuilder to render our list item
- We’ll look at the IsCurrentAction method next, it checks if the specified action/controller is the one currently being presented to the user
- If this is the current Action then set the list item’s class to “current”
- Put the link inside the li tag
IsCurrentAction is pretty straightforward too…
So how would you use your new helper methods?
This will render the list items and put a class=”current” attribute on the one for the page currently being viewed.
Now an obvious problem with this approach is that you can’t embed sub menus (ULs within LIs). The way around this is to mimic the MVC framework itself and introduce new BeginListItem and EndListItem methods (ASP.NET MVC has BeginForm and EndForm).
This opens the li tag. The EndListItem method closes it.
And we can use these methods as follows.
Up next is how to spice this menu up and make it all “interactivy” using JQuery,