OdeToCode IC Logo

ASP.NET MVC - Highlight Current Link

Monday, August 27, 2012

In an ASP.NET MVC application, there are many different solutions you might use to highlight the menu item for the current location.

Highlight current item

Here's one - a custom HTML helper for building menu items. The custom helper will detect if the link is a link to the current action, and if so the helper adds an additional CSS class to the link (currentMenuItem).

public static MvcHtmlString MenuLink(
this HtmlHelper helper,
string text, string action, string controller)
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];

if(String.Equals(action, currentAction as string,
String.Equals(controller, currentController as string,

return helper.ActionLink(
text,action, controller, null,
new { @class="currentMenuItem"}
return helper.ActionLink(text, action, controller);

Use the helper when building a menu in your Layout view.

<li>@Html.MenuLink("Contact", "Contact", "Home")</li>

And don't forget to add some styles to make the current link appear differently from the other links.

ul#menu li a {
background: none;
color: #999;
padding: 5px;
border-radius: 15px;
text-decoration: none;

ul#menu li a.currentMenuItem {
background-color: black;
color: white;

Another variant would be for the helper check the current controller name only when deciding to mark a link as current.