I\'m wondering how is it possible to add a CSS Class to the current page in your navigation when using ASP.NET MVC 3? Here is my navigation in my _Layout.cshtml file:
<
I would recommend using an extension method for this. Something like:
public static HtmlString NavigationLink(
this HtmlHelper html,
string linkText,
string actionName,
string controllerName)
{
string contextAction = (string)html.ViewContext.RouteData.Values["action"];
string contextController = (string)html.ViewContext.RouteData.Values["controller"];
bool isCurrent =
string.Equals(contextAction, actionName, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(contextController, controllerName, StringComparison.CurrentCultureIgnoreCase);
return html.ActionLink(
linkText,
actionName,
controllerName,
routeValues: null,
htmlAttributes: isCurrent ? new { @class = "current" } : null);
}
Then you can use it in your View by including the namespace of your extension and just calling your method:
@using MyExtensionNamespace;
...
@Html.NavigationLink("Product Search", "Index", "Home")
| @Html.NavigationLink("Orders", "Index", "Orders")
| @Html.NavigationLink("My Account", "MyAccount", "Account")
| @Html.NavigationLink("Logout", "LogOff", "Account")
This has the benefit of keeping your razor a little cleaner and is easily reusable in other views.