When I want a specific menu link to be active at a given page, I'm using this approach in Razor:
On the master layout I have these checks:
var active = ViewBag.Active;
const string ACTIVE_CLASS = "current";
if (active == "home")
{
ViewBag.ActiveHome = ACTIVE_CLASS;
}
if (active == "products")
{
ViewBag.ActiveProducts = ACTIVE_CLASS;
}
etc.
The html menu on the master layout:
<ul>
<li class="@ViewBag.ActiveHome"><a href="/">Home</a></li>
<li class="@ViewBag.ActiveProducts"><a href="@Url.Action("index", "products")">Products</a></li>
</ul>
When specifying which layout page to use on a different view:
@{
ViewBag.Active = "home";
Layout = "~/Views/Shared/_Layout.cshtml";
}
Is there a better approach to sepcify active links, than the one I'm currently using?
here is an extention on Darin's class to insert html in the link text rather than a simple text
and use it like this:
Use this InnerHtml if you'd like to include HTML formatting in your text;
text could be "<b>Bold</b>Normal";
This code worked great for me, even on a new Visual Studio 2013 MVC5/Bootstrap project. Note also that you could change the li.AddCssClass("active"); line to point to a custom class if you want to leave the Bootstrap "active" class alone. I added one called "activemenu" in the project's Site.css file and did any specific navbar styling changes I wanted there.
The line in the code above was just changed to this to get it all working:
In Site.css I added a simple class for my purpose:
Alternatively you could change the background color and/or border, etc...
Expanding on Darin's example, here's the full class which adds additional optional parameters for RouteValues and HtmlAttributes on the helper. In effect, it behaves just like the base ActionLink.
And in the View folder's web.config:
A better approach is to use a HTML helper:
and then:
To make the above work you need your views to recognize your extension: In Web.config in the Views folder, add
<add namespace="yourNamespacehere.Helpers" />
inside the namespaces tag. Then build your project and close and re-open the view you are adding this to.then based on the current action and controller the helper will add or not the
active
class when generating the anchor.Updated for RC2 - For those wondering how to do this in MVC6 / Asp.Net 5 - similar but subtly different. There's now no
MvcHtmlString
, and theRouteData
works completely differently. Also, the context object should now beIHtmlContent
rather thanHtmlHelper
.