Highlight the tab according to action and controller in asp.net MVC

By 1st August 2019ASP.NET, C#, MVC

In Menu bar, while navigating, “Active” class will add in menu item according to your controller and action, that is fixed by you in your html code.

Just use this extension method in your menu item class.

 

public static string IsActive(this HtmlHelper html,
                                      string control,
                                      string action)
        {
            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" : ""; //Here you can change class name according to your theme like "active" or anything
        }

Now you have to use this method as HTML helper in your razor page.



<li class="@Html.IsActive("About","Index")">
 <a href="@Url.Action("Index","About")">About Us</a>
</li>

                       
                        
 
<li class="@Html.IsActive("Contact","Index")">
 <a href="@Url.Action("Index","Contact")">Contact Us</a>
 </li>


Now if your controller and action will “About” and “Index” then “active” named class will add in you li class.