In my last post, I talked about a nuget package called T4MVC. In this post, I’m going to show how to show active menu item in MVC 5 with the help of T4MVC.
The problem
When starting the default MVC web application from Visual Studio, the main navigation menu does not show the active menu item or selected page.

The navigation menu does not show the selected page is About.
Solution
Firstly, install T4MVC nuget package. Then I have an extension method for WebViewPage to return the CSS class ‘active’ (this works with Bootstrap but you can use whatever custom CSS class name) if the requested page matches the controller and action.
public static class WebViewPageExtensions { public static string GetMenuItemCssClass(this WebViewPage view, string controller, string action) { if (view.ViewContext.RouteData.Values["action"].ToString() == action && view.ViewContext.RouteData.Values["controller"].ToString() == controller) { return "active"; } return string.Empty; } }
In the _layout.cshtml view, reference the WebViewPage and replace the action links with the followings.
<li class="@this.GetMenuItemCssClass(MVC.Home.Name, MVC.Home.ActionNames.Index)">@Html.ActionLink("Home", MVC.Home.Index())</li> <li class="@this.GetMenuItemCssClass(MVC.Home.Name, MVC.Home.ActionNames.About)">@Html.ActionLink("About", MVC.Home.About())</li> <li class="@this.GetMenuItemCssClass(MVC.Home.Name, MVC.Home.ActionNames.Contact)">@Html.ActionLink("Contact", MVC.Home.Contact())</li>
This adds a CSS class ‘active’ to the list item that matches the controller and action of the requested page.

The About menu item is selected on About page.