I'm trying to add an"active" class to my bootstrap navbar in MVC, but the following doesn't show the active class when written like this:
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home", null, new {@class="active"})</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
This resolves to what looks like a correctly formatted class, but doesn't work:
<a class="active" href="/">Home</a>
In the Bootstrap documentation it states that 'a' tags shouldn't be used in the navbar, but the above is how I believe is the correct way of adding a class to an Html.ActionLink. Is there another (tidy) way I can do this?
My Solution to this problem is
A better way may be adding an Html extension method to return the current path to be compared with link
the answer by @dombenoit works. Though it introduces some code to maintain. Check this syntax out:
Notice the use of
.SetLinksActiveByControllerAndAction()
method.If you wonder what makes this syntax possible, check out TwitterBootstrapMVC
if is it is not showing at all, the reason is that you need two @ sign:
BUT, I believe you might need to have the active class on the "li" tag not on the "a" tag. according too bootstrap docs (http://getbootstrap.com/components/#navbar-default):
therefore your code will be:
Hope this helps, below is how your menu can be:
And add below MVC helper function below the html tag.
I referred the answer from http://questionbox.in/add-active-class-menu-link-html-actionlink-asp-net-mvc/
I believe here is a cleaner and smalller code to do get the selected menu being "active":
We also can create
UrlHelper
from RequestContext which we can get from MvcHandler itself. Therefore I beleive for someone who wants to keep this logic in Razor templates following way would be helpful:AppCode
.HtmlHelpers.cshtml
Create a helper in there:
Then we can use on our views like this:
Hope that it helps to someone.