MVC Highlight Active Navigation Tab

The top navigation bar on most sites has some form of highlight to allow the user to quickly see what section of the site they are viewing. In MVC this can be accomplished with a simple HTML and CSS modification.

Modify the Controller(s)

You will need to pass a variable <code>@currentPage</code> to your view from the appropriate controller(s).

//
// GET: /Product/

public ActionResult Index()
{
	ViewBag.CurrentPage = "Products";

	return View();
}

Modify the Shared View

You will need to modify the <body> tag of _Layout.cshtml to include an id. In the code (below) I go the extra step of converting the string to lowercase to match the CSS no matter how a developer types the CurrentPage in the controller.

@{
    string currentPage = @ViewBag.CurrentPage.ToLower();
}
<body class="homepage" id="@currentPage">

Modify the CSS

If using a minified CSS this part can be a bit of a pain, but still possible. In your CSS file add code or modify an existing block, a:hover for example, to include the body tags.

body#home a#home,
body#blog a#blog,
body#apparel a#apparel,
body#comics a#comics,
body#gadgets a#gadgets,
body#games a#games,
body#movies a#movies
{
	background: #d52349;
	color: #fff !important;
	font-weight: 700;
}

Tying it All Together

Whenever a bodyID matches the CSS, the active section will be highlighted.

07072014_001

Further Reading

Original credit goes to Bhavin Surela – Highlighting current page in MVC 3 – Slick Trick.