ASP.net MVC - Navigation and highlighting the “current” link

前端 未结 9 1613
清酒与你
清酒与你 2020-12-30 11:10

When you create a new MVC project it creates a Site.master with the following markup:

    <
9条回答
  •  鱼传尺愫
    2020-12-30 11:37

    Thanks to @codingbadger for the solution.

    I had to get my nav-links highlighted on multiple actions so I decided to add a few more parameters that contain the controller-action pairs and it'll highlight the link if either of those combinations is accessed too. And, in my case, the highlighting class was to be applied to a

  • element.

    I'm putting my code here hoping it will help someone in the future:

    • Here's the helper method:

      /// 
      /// The link will be highlighted when it is used to redirect and also be highlighted when any action-controller pair is used specified in the otherActions parameter.
      /// 
      /// The CSS class that will be applied to the selected link
      /// A list of tuples containing pairs of Action Name and Controller Name respectively
      public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable> otherActions)
      {
          string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
          string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
      
          if ((actionName == currentAction && controllerName == currentController) || 
              (otherActions != null && otherActions.Any(pair => pair.Item1 == currentAction && pair.Item2 == currentController)))
          {
              return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}");
          }
      
          return new MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText, actionName, controllerName)}");
      }
      
    • And, here's an example of how to use it:

      @Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple[] { new Tuple("Index", "Eligibility"), new Tuple("RecheckEligibility", "Eligibility") }) @Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")

提交回复
热议问题