【问题标题】:How to append active class to existing class on clicked menu items?如何在单击的菜单项上将活动类附加到现有类?
【发布时间】:2016-12-09 01:42:57
【问题描述】:

我有menu items on master page,如果用户单击该菜单项,我希望将其显示为活动状态。我想将 Active 附加到现有类以使其处于活动状态。

_Layout.cshtml:

 <div class="menu-items-navigation">
  <div class="Classy-item" class="@Html.IsSelected(actions: "Index", controllers: "Classy")">
      <a href="@Url.Action("Index", "Classy")"   >
          <div style="padding-top: 50px;">Classy Items</div>
       </a>
   </div>
   <div class="Regular-stuff">
      <a href="@Url.Action("Index", "RegularStuff")">
           <div style="padding-top: 50px;">Regular Stuff</div>
      </a>
   </div>

   <div class="Popular-Vessels">
       <a href="@Url.Action("Index", "PopularVessels")">
           <div style="padding-top: 50px;">Popular Vessels</div>
       </a>
   </div>
 </div>

现在,如果我希望此菜单项为 Active,我有 1 个称为 Active 的类,如果用户单击这 3 个菜单项中的任何一个,我想将其分配给该 div。

例如,如果我想在上面打上Regular Stuff as Active when user clicks,那么它将是这样的:

<div class="Regular-stuff Active">

如果用户点击 Classy Item 则:

<div class="Classy-item Active">

代码取自这里Reference:

 public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "Active")
        {
            ViewContext viewContext = html.ViewContext;
            bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;

            if (isChildAction)
                viewContext = html.ViewContext.ParentActionViewContext;

            RouteValueDictionary routeValues = viewContext.RouteData.Values;
            string currentAction = routeValues["action"].ToString();
            string currentController = routeValues["controller"].ToString();

            if (String.IsNullOrEmpty(actions))
                actions = currentAction;

            if (String.IsNullOrEmpty(controllers))
                controllers = currentController;

            string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
            string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();

            return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
                cssClass : String.Empty;
        }

但是我在这里感到困惑的是,当单击特定菜单项时如何对这个 Isselected 方法进行分类,因为我不能在 div 上使用类属性 2 次。

【问题讨论】:

    标签: c# css asp.net asp.net-mvc


    【解决方案1】:

    你是对的,你不能两次声明class属性,但是你可以像这样组合它们:

    <div class="Classy-item @Html.IsSelected(actions: "Index", controllers: "Classy")">
    

    如果没有选择会渲染:

    <div class="Classy-item "> 
    

    如果选中则渲染它:

    <div class="Classy-item Active">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      相关资源
      最近更新 更多