我在母版页上有菜单项
,如果用户单击该菜单项,我希望它显示为事件状态。我想将 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/