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?
Here is a way to implement this as an MVC helper:
It can then be used similar to the following:
A good article on MVC helpers can be found here: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
Thanks to @codingbadger for the solution.
I had to get my nav-links highlighted on multiple actions so I decided to add a few more parameters that contain the controller-action pairs and it'll highlight the link if either of those combinations is accessed too. And, in my case, the highlighting class was to be applied to a
<li>
element.I'm putting my code here hoping it will help someone in the future:
Here's the helper method:
And, here's an example of how to use it:
First Make a Helper Class and HTML Helper method
And in View or Layour Section Just Call the Helper Method with appropriate Conntroller and Action.
this will add "active" string in class attribute and it will show like
Check out this blog post
It shows how to create an HTML Extension that you call instead of the usual
Html.ActionLink
The 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
selected
class in your CSS and then in your views add ausing
statement at the top.@using ProjectNamespace.HtmlHelpers
And use the
MenuLink
instead ofActionLink
@Html.MenuLink("Your Menu Item", "Action", "Controller")
I Used this approach with a htmlhelper for the problem:
and for the view