我的应用程序中有一些菜单项,如下所示:
现在,当用户点击任何菜单项时,我想让它处于活动状态,就像用户点击统计数据一样,我想让它处于活动状态,这就是我现在正在做的事情,并且工作正常。
_Layout.cshtml :
<div class="Menu @Html.IsSelected(actions: "Index", controllers: "Statistics", class: "active")" ><a href="/Statistics/Index">Stats</a></div>
<div class="Menu @Html.IsSelected(actions: "Index", controllers: "Tax", class: "active")"><a href="/Tax/Index">Tax</a></div>
<div class="Menu @Html.IsSelected(actions: "Index", controllers: "Skills", class: "active")"><a href="/Skills/Index">Skills</a></div>
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = null)
{
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;
//for passing multiple comma seperated Action.
//For Eg:class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")"
string[] acceptedActions = actions.Trim().Split(',').Distinct().Select(t=>t.ToLower().ToString()).ToArray();
string[] acceptedControllers = controllers.Trim().Split(',').Distinct().Select(t=>t.ToLower().ToString()).ToArray();
return acceptedActions.Contains(currentAction.ToLower()) && acceptedControllers.Contains(currentController.ToLower()) ?
cssClass : String.Empty;
}
但现在我可以从统计数据和税页访问1个常用页面:
等级
用户从统计信息转到此页面时的网址:
http://localhost:1231/Rank/Index?type=stats&Id=21
用户从统计信息转到此页面时的网址:
http://localhost:1231/Rank/Index?type=Tax&Id=48
因此,当用户从“统计”页面进入“排名”页面时,我想激活“统计”菜单,并在用户从“税”页面进入排名页面时激活“税”菜单项。
答案 0 :(得分:1)
你这样做太复杂了。试试这个:
@{ string url = null; }
@{ url = Url.Action("Index", "Statistics"); }
<div class="Menu @(url == Request.Url.AbsolutePath ? "active" : null)">
<a href="@url">Stats</a>
</div>
@{ url = Url.Action("Index", "Tax"); }
<div class="Menu @(url == Request.Url.AbsolutePath ? "active" : null)">
<a href="@url">Tax</a>
</div>
@{ url = Url.Action("Index", "Skills"); }
<div class="Menu @(url == Request.Url.AbsolutePath ? "active" : null)">
<a href="@url">Skills</a>
</div>
换句话说,您只需要一个简单的三元组来比较链接的URL和当前的URL。使用Request.Url.AbsolutePath
以便忽略查询字符串。设置url
变量只是为了防止必须多次调用Url.Action
,让事情变得干涸。
答案 1 :(得分:0)
它很简单,就像一个技巧
css
Active
并设置您想要显示的任何颜色。Active
的类仅添加到该元素。