[ASP.NET MVC] Views – How to Add “selected” Class to the Menu Item

ASP.NET MVC application templates provide you with the pre-configured controllers and views for your convenience.

Templates also provide the default tab menus (“Home” and “About”) and pretty nice CSS styles. If you look at the “Site.css” file, you can find the “ul#menu li.selected a” section, which styles the selected menu item. But the application template does not set the “selected” class to the selected menu item.

In this post, I will show you how to do this using the custom “Html Helper” method.

1. _Layout.cshtml

Menu items are defined in the layout file.

<nav>
  <ul id="menu">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
  </ul>
</nav>

 

2. Site.css

The default style of the selected menu is like this:

ul#menu li.selected a {
  background-color: #034af3;
  color: #e8eef4;
}

The style expects that the selected menu item has the “selected” class.

 

3. Creating Html Helper Method

  • Create a “HtmlHelpers” folder in your project
  • Create a static class
  • Define a static method with the first parameter “this HtmlHelper helper
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;

namespace MyWebApp.WebUI.HtmlHelpers
{
  public static class HtmlHelperExtensions
  {
    public static string ActivePage(this HtmlHelper helper, string controller, string action)
    {
      string classValue = "";

      string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
      string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();

      if (currentController == controller && currentAction == action)
      {
        classValue = "selected";
      }

      return classValue;
    }
  }
}

 

4. Referring the Html Helper Method in a View

To refer to the helper method in a view, you need to include the namespace with the “using” statement

@using MyWebApp.WebUI.HtmlHelpers

Or you can modify the “Web.config” file in the “Views” folder. (Note that it is not the root config file.)

<system.web.webPages.razor>
  <host ... />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      ...
      <add namespace="MyWebApp.WebUI.HtmlHelpers" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

 

5. Modifying the View

Let’s change the menu.

<nav>
  <ul id="menu">
    <li class="@Html.ActivePage("Home", "Index")">@Html.ActionLink("Home", "Index", "Home")</li>
    <li class="@Html.ActivePage("Home", "About")">@Html.ActionLink("About", "About", "Home")</li>
  </ul>
</nav>

If you want to add the “selected” class directly to the <a> element rather than <ul> element, you can do like this:

<nav>
  <ul id="menu">
    <li>@Html.ActionLink("Home", "Index", "Home", null, new { @class = Html.ActivePage("Home", "Index") })</li>
    <li>@Html.ActionLink("About", "About", "Home", null, new { @class = Html.ActivePage("Home", "About") })</li>
  </ul>
</nav>

12 thoughts on “[ASP.NET MVC] Views – How to Add “selected” Class to the Menu Item

  1. Works great thanks!

    I added a variation that only checks the controller so that the top level menu item still gets highlighted when another view is selected besides Index (that isn’t reflected in the top level menu) – and that also works, where required.

    I’d similarly like to add another variation to cater for a menu selection with a parameter – for example, where only items starting with a specific letter of the alphabet is selected, instead of listing everything with just a controller and action, where A to Z menu options can be selected to refine the list.

    I can get this to work by checking for a specific parameter value and highlighting the relevant selected menu item at each letter’s menu item manually – but that seems clumsy and I’d prefer to use this much cleaner approach without needing a check for a parameter value for each menu item by just adding a variation to the HTML Helper method (such as perhaps ActivePageI for an Item) that also caters for a parameter (such as “Ä”), besides just the controller and action – but I’m a newbie and don’t know what the system name for a parameter (equivalent to “controller” and “action”) might be?

    I suspect the solution would potentially help many other newbies and would really appreciate your help, please.

  2. I am running into errors trying to do this.

    In Step 3 (Creating Html Helper Method) I am having an issue with the ViewContext.

    The error states, “‘TestSite.HtmlHelpers.HtmlHelper’ does not containg a definition for ‘ViewContext’ and no extension method ‘ViewContext’ accepting a first argument of type ‘TestSite.HtmlHelpers.HtmlHelper’ could be found (are you missing a using directive or an assembly reference?)”

    How can I fix this?

  3. Also, in the _Layout.cshtml file, Html.ActivePage is not working either.

    The error states, “‘System.Web.Mvc.HtmlHelper’ does not contain a definition for ‘ActivePage’ and no extension method ‘ActivePage’ accepting a first argument of type ‘System.Web.Mvc.HtmlHelper’ could be found (are you missing a using directive or an assembly reference?”

  4. Hello,
    great solution. But I have a Problem with the CSS class ul#menu li.selected a {…). I use the version:

    The method ActivePage returns the string “selected”. But the CSS class cannot be found.

    What did you mean with:
    “If you want to add the “selected” class directly to the element rather than element”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s