How to set active class in li tag in mvc razor helper

Set Active class in li tag of mvc

Follow the steps of this post to create the custom extension in mvc.

Now we have created the Utilities class as below for setting the active class as well as we have extension method for creating the nav links and it will take care of active class in li tag just like in laravel, ruby we do.

namespace Audito.Utilities
   public static class HtmlUtilities
      public static string IsActive(this HtmlHelper html,
               string action,
               string control)
            var routeData = html.ViewContext.RouteData;

            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];

            // both must match
            var returnActive = control == routeControl && action == routeAction;

            return returnActive ? "active" : "";

      public static string NavLink(this HtmlHelper html, string text, string action, string controller, string extra = "")
         var liTag = "<li class="+IsActive(html, action, controller)+">";
         liTag += "<a href="+ LinkExtensions.ActionLink(html, "", action, controller) + ">"+text+"</a>";
         liTag += "</li>";
         return liTag;

Now we can make use of the above methods and create the links,

	<li class="@Html.IsActive(">@Html.ActionLink("Index", "Home", "Home")</li>


@Html.NavLink("Index", "Home", "Home")

This will create the li tag and set the active class

Leave a Reply