c# - 如何在单击的菜单项上将事件类附加到现有类?

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

我在母版页上有菜单项,如果用户单击该菜单项,我希望它显示为事件状态。我想将 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 在用户点击时激活,那么它将是这样的:

<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;
        }

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

最佳答案

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

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

如果未选中,将呈现:

<div class="Classy-item "> 

或者如果选中则渲染它:

<div class="Classy-item Active">

关于c# - 如何在单击的菜单项上将事件类附加到现有类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741837/

相关文章:

c# - ASP :dropdownlist width: How to make the control narrower than the dropdown list

c# - 在 Windows 窗体中向 SplitContainer 添加面板

c# - 每小时生成时间范围

css - 像 facebook 横幅一样在浏览器中跨越图像,但现在是图像

c# - 正确运行 SerializeObject 方法?

html - 让 <body> 填满整个屏幕?

css - iFrame 内容被挤压到 IE 中的滚动框中

c# - 防伪 token 问题已解决但对项目产生影响后很奇怪

asp.net - 在控制台应用程序和 asp.net Web 应用程序之间共享配置

c# - 静态函数并发 ASP.NET