我有一个位于母版页上的菜单项,如果用户点击该菜单项,我希望将其标记为活动状态。我想要添加“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的类。当用户点击这3个菜单项中的任意一个时,我想将此类赋予此div。
例如,如果我想让用户点击常规物品
后成为活动状态
,则应按以下方式进行:
<div class="Regular-stuff Active">
如果用户点击“优雅项目”:
<div class="Classy-item Active">
以下代码源自这里:
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上两次使用class属性。