Setting the active link in a Twitter Bootstrap Navbar in ASP.NET MVC

If you have used Twitter Bootstrap before you will probably know that it has a Navbar component so you can easily build navigation for a website. One of the features of the Navbar is being able to set which of the links within it is the currently active one, so this can displayed to the user.

As the Navbar needs to appear on every page it would be placed into your _Layout.cshtml (assuming you’re using Razor) and would look something like this

 ...
 <div class="navbar navbar-fixed-top">
	<div class="navbar-inner">
		<div class="container">
			<a class="brand" href="#">Title</a>
			<ul class="nav">
				<li><a href="#">Link 1</a></li>
				<li><a href="#">Link 2</a></li>
				<li><a href="#">Link 3</a></li>
				<li><a href="#">Link 4</a></li>
			</ul>
		</div>
	</div>
</div>
...

So, how do you find out which is the active link and set the active class on the <li> tag? I’ve created an HtmlHelper extension method to do just that!

And it can be used like this:

...
<div class="navbar navbar-fixed-top">
	<div class="navbar-inner">
		<div class="container">
			<a class="brand" href="#">Title</a>
			<ul class="nav">
				@Html.MenuLink("Link 1","Index","Home")
				@Html.MenuLink("Link 2","Index","Home")
				@Html.MenuLink("Link 3","Index","Home")
				@Html.MenuLink("Link 4","Index","Home")
			</ul>
		</div>
	</div>
</div>
...

This will output a <li> tag with an anchor tag inside it and will add class=”active” to the <li> tag if it is the active one.
Note: depending on the namespace of your HtmlHelper extension class you may need to add a using statement to the top of the Razor file, such as

@using MyProject.Web.Helpers