Dismissile Dismissile - 1 year ago 100
C# Question

ASP.net MVC - Navigation and highlighting the "current" link

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>

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?

Answer Source

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 appends class="selected" to the list item that is currently active.

You can then put whatever formatting/highlighting you want in your CSS


Just adding some code to rather than just a link.

public static class HtmlHelpers

    public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
                                        string linkText,
                                        string actionName,
                                        string controllerName

        string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
        string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

        if (actionName == currentAction && controllerName == currentController)
            return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" });

        return htmlHelper.ActionLink(linkText, actionName, controllerName);


Now you need to define your selected class in your CSS and then in your views add a using statement at the top.

@using ProjectNamespace.HtmlHelpers

And use the MenuLink instead of ActionLink

@Html.MenuLink("Your Menu Item", "Action", "Controller")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download