As a base for discussion. Create a standard ASP.NET MVC Web project.
It will contain two menu items in the master page:
<div id="menucontainer">
<ul id="menu">
<li>
<%= Html.ActionLink("Home", "Index", "Home")%></li>
<li>
<%= Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
How can I set the visual CSS style indicating the current page. For example, when in the About page/controller, I essentially would like to do this:
<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>
And, of course, when on the home page:
<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>
(Having a CSS style names current that visually indicates in the menu that this is the current page.)
I could break out the menu div from the master page into a content place holder, but that would mean that I must put the menu on every page.
Any ideas, is there a nice solution to this?
I recently created an HTML Helper for this that looks like:
The Implementation looks like this:
The easiest way is to get the current controller and action from the ViewContext's RouteData. Note the change in signature and use of @ to escape the keyword.
Note that you could combine this an HtmlHelper extension like @Jon's and make it cleaner.
Where MenuActionLink is
It might just be that it's the 5th parameter, so slot a null before your html attribute. This post here describes it as such, though you can pass in some stuff on the 4th arguement, the 5th is specifically for HTMLattributes
If you are using T4MVC, you can use this:
Chucked this together in 5mins, I could probably refactor it, but should give you the basic idea, its probably most useful for smaller sites.