如何在单击的菜单项上将活动类附加到现有类?

时间:2016-08-03 11:06:14

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

我有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,我有一个名为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次。

1 个答案:

答案 0 :(得分:3)

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

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

如果未选择将呈现:

<div class="Classy-item "> 

如果选择则渲染:

<div class="Classy-item Active">