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?
Add '.ToString' to improve comparing on ASP.NET MVC
--
I realized that this problem was a common problem for some of us, so I published my own solution using nuget package. Below you can see how it works. I hope that will be useful.
Note:This nuget package is my first package. So if you see a mistake, please give feedback. Thank you.
Install Package or download source code and add your Project
Add your pages to an enum
Put Filter to top of your Controllor or Action
And use it In your header layout like this
More Info: https://github.com/betalgo/MvcMenuNavigator
I have make combination of answers above and made my solution.
So..
First in razor block create one string variable which will contain name value of controller and action that is called by user.
Then use combination of HTML and Razor code:
I think, that this is good because you don't need to access "ViewContext.RouteData.Values" each time to get controller name and action name.
is possible with a lambda function
then usage
I know this question is old, but I will just like to add my voice here. I believe it is a good idea to leave the knowledge of whether or not a link is active to the controller of the view.
I would just set a unique value for each view in the controller action. For instance, if I wanted to make the home page link active, I would do something like this:
Then in my view, I will write something like this:
When you navigate to a different page, say Programs, ViewBag.Home does not exist (instead ViewBag.Programs does); therefore, nothing is rendered, not even class="". I think this is cleaner both for maintainability and cleanliness. I tend to always want to leave logic out of the view as much as I can.
I manged to do this by adding a view bag parameter in asp.net mvc. Here what have i done
Added
ViewBag.Current = "Scheduler";
like parameter in each pageIn layout page
This solved my problem.