Home >Web Front-end >CSS Tutorial >How to Efficiently Add the 'Active' Class to ASP.NET MVC's Html.ActionLink for Bootstrap Navigation?
In ASP.NET MVC, adding an "active" class to the bootstrap navbar is essential. However, the common approach of adding it to the element doesn't align with Bootstrap's guidelines.
Bootstrap requires the "active" class to be applied to the
<ul class="nav navbar-nav"> <li class="active">@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul>
Rather than manually adding the "active" class to each
<ul class="nav navbar-nav"> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li> </ul>
An even more elegant solution is to create an HtmlHelper extension method:
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected") { var viewContext = html.ViewContext; var isChildAction = viewContext.Controller.ControllerContext.IsChildAction; if (isChildAction) viewContext = html.ViewContext.ParentActionViewContext; var routeValues = viewContext.RouteData.Values; var currentAction = routeValues["action"].ToString(); var currentController = routeValues["controller"].ToString(); var acceptedActions = actions.Trim().Split(',').Distinct().ToArray(); var acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray(); return (acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController)) ? cssClass : ""; }
Usage:
<ul> <li class="@Html.IsSelected(actions: "Home", controllers: "Default")"> <a href="@Url.Action("Home", "Default")">Home</a> </li> <li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")"> <a href="@Url.Action("List", "Default")">List</a> </li> </ul>
The above is the detailed content of How to Efficiently Add the 'Active' Class to ASP.NET MVC's Html.ActionLink for Bootstrap Navigation?. For more information, please follow other related articles on the PHP Chinese website!