Adding the Active Class to Html.ActionLink
In ASP.NET MVC, it's common to set the "active" class on navigation elements to indicate the current active page. However, adding the class directly to the tag may not be the desired approach.
Bootstrap Considerations
For Bootstrap, the active class is typically applied to the <li> element rather than the tag. Therefore, you should modify your code to resemble this:
<ul>
Dynamic Class Assignment
To automate the process of assigning the active class based on the current page, you can use the following approach:
<ul>
By using the ViewContext.RouteData.Values property, you can automatically determine the current action and controller. The ternary operator allows you to conditionally add the active class based on the action being performed.
HtmlHelper Extension
For a cleaner and more elegant solution, you can create an HtmlHelper extension method:
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected") { // Get the current action and controller string currentAction = html.ViewContext.RouteData.Values["action"].ToString(); string currentController = html.ViewContext.RouteData.Values["controller"].ToString(); // Create arrays of accepted actions and controllers string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray(); string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray(); // Check if the current action and controller match any of the accepted values return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ? cssClass : string.Empty; }
This extension method allows you to easily assign the active class using the following syntax:
<li>
The above is the detailed content of How to Efficiently Add the 'Active' Class to ASP.NET MVC Navigation Links?. For more information, please follow other related articles on the PHP Chinese website!