A fairly-common UX pattern is highlighting the link within a menu that corresponds to the page or section that a user is currently on.  This can be done quite easily in ASP.NET MVC.  Here’s a simple, strongly-typed extension method that you can drop in.


So here’s what we’re trying to achieve (shamelessly borrowed from ux.stackexchange.com):


The “Download” menu item is highlighted because the user is currently on the Download page.  Assuming that there’s a route associated to each page, we can achieve the same thing in MVC using this extension method (note that it requires the Mvc4Futures package):

public static MvcHtmlString MenuLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText) where TController : Controller
    var linkRoute = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);

    var currentRoute = helper.ViewContext.RouteData.Values;

    var actionLink = helper.ActionLink(action, linkText);

    var isCurrentRoute = linkRoute["controller"].ToString() == currentRoute["controller"].ToString() &&
        linkRoute["action"].ToString() == currentRoute["action"].ToString();

    return MvcHtmlString.Create(string.Format("<li{0}>", isCurrentRoute ? " class=\"active\"" : string.Empty) + actionLink + "</li>");

Here’s how to use it in a Razor view, taken from Heroic Support:

<div class="nav-collapse collapse">
    <ul class="nav">
        @(Html.MenuLink<DashboardController>(c => c.Index(), "Dashboard"))
        @(Html.MenuLink<TicketController>(c => c.Add(), "New Ticket"))

Note that we’re using Twitter Bootstrap, and our link is being rendered inside of a navbar component, so we’ll get a nice highlighted link.  Here’s the final product as it appears in Heroic Support:


Simple and strongly-typed, the way MVC should be.