Home > Web Front-end > CSS Tutorial > How to Efficiently Add the 'Active' Class to ASP.NET MVC Navigation Links?

How to Efficiently Add the 'Active' Class to ASP.NET MVC Navigation Links?

Patricia Arquette
Release: 2024-12-31 21:49:11
Original
181 people have browsed it

How to Efficiently Add the

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>
Copy after login
Copy after login

Dynamic Class Assignment

To automate the process of assigning the active class based on the current page, you can use the following approach:

<ul>
Copy after login
Copy after login

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) &amp;&amp; acceptedControllers.Contains(currentController) ?
    cssClass : string.Empty;
}
Copy after login

This extension method allows you to easily assign the active class using the following syntax:

<li>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template