try-catch-FAIL

Failure is inevitable

NAVIGATION - SEARCH

Highlighting the Current Link in a Menu with ASP.NET MVC

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):

image

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"))
    </ul>
   ...
</div>

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:

image

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

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus