Add "active" class to menu in ASP.NET MVC - Helper

The helper will do it for you


Let's take a look at the code.


You can dynamically set the active class in the ASP.NET MVC project. There are a way to solve the issue.


For example, when the user is looking at the home page, the menu looks like this.


Let's take a look at the code.


<li class="active">
    <a href="home.html">
        <p>Home</p>
    </a>
</li>
<li>
    <a href="test1.html"> 
        <p>Test 1</p>
    </a>
</li>
<li>
    <a href="test2.html"> 
        <p>Test 2</p>
    </a>
</li>
<li>
    <a href="test3.html"> 
        <p>Test 3</p>
    </a>
</li>

d1.PNG

The custom helper will do it for you. ( You can use a custom helper to add the "active" class to your menu )


If user is on the "Home" page, the helper will highligth the "Home" menu item like above.


The helper class match the requested URL to the menu item.


Menu is in the Layout page, so it's comman for all the pages.


Using an HtmlHelper extension, this helper set the "active" class using the route data from the application as follows.


using System.Web.Mvc;
using System.Web.Routing;

namespace WebApplication2.Extensions
{
    public static class Helper
    {
        public static string IsActive(this HtmlHelper helper, string controller, string action)
        {
            ViewContext context = helper.ViewContext;

            RouteValueDictionary values = context.RouteData.Values;

            string _controller = values["controller"].ToString();

            string _action = values["action"].ToString();

            if ((action == _action) && (controller == _controller))
            {
                return "active";
            }
            else
            {
                return "";
            }
        }
    }
}

The _LayoutPage1.cshtml file looks like this.


@using WebApplication2.Extensions
.
.
.

<li class="@Html.IsActive("Home", "Index")">
    <a href="/Home/Index">
        <p>Home</p>
    </a>
</li>
<li class="@Html.IsActive("Test1", "Index")">
    <a href="/Test1/Index"> 
        <p>Test 1</p>
    </a>
</li>
<li class="@Html.IsActive("Test2", "Index")">
    <a href="/Test2/Index"> 
        <p>Test 2</p>
    </a>
</li>
<li class="@Html.IsActive("Test3", "Index")">
    <a href="/Test3/Index"> 
        <p>Test 3</p>
    </a>
</li>