When you create a new MVC project it creates a Site.master with the following markup:
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
I would like to put code in here that will highlight the current link if I am on that page.
If I add another link such as:
<li><%: Html.ActionLink("Products", "Index", "Products")%></li>
I would want the Products link to be active (using a css class like .active) if I’m on any action in the Products controller.
The About link should be active if I’m on the HomeController About action. The Home link should be active if I’m on the Index action of the HomeController.
What is the best way to do this in MVC?
Check out this blog post
It shows how to create an HTML Extension that you call instead of the usual
Html.ActionLinkThe extension then appendsclass="selected"to the list item that is currently active.You can then put whatever formatting/highlighting you want in your CSS
EDIT
Just adding some code to rather than just a link.
Now you need to define your
selectedclass in your CSS and then in your views add ausingstatement at the top.@using ProjectNamespace.HtmlHelpersAnd use the
MenuLinkinstead ofActionLink@Html.MenuLink("Your Menu Item", "Action", "Controller")