有助手负责将Active类添加到菜单中。
public static class HtmlHelpers
{
public static string IsSelected(this IHtmlHelper html, string controller = null, string action = null, string status = null, string cssClass = null)
{
if (String.IsNullOrEmpty(cssClass))
cssClass = "active";
string currentAction = (string)html.ViewContext.RouteData.Values["action"];
string currentController = (string)html.ViewContext.RouteData.Values["controller"];
string currentStatus = (string)html.ViewContext.RouteData.Values["status"];
if (String.IsNullOrEmpty(controller))
controller = currentController;
if (String.IsNullOrEmpty(action))
action = currentAction;
if (String.IsNullOrEmpty(status))
status = currentStatus;
return controller == currentController && action == currentAction && status == currentStatus ?
cssClass : String.Empty;
}
public static string PageClass(this IHtmlHelper htmlHelper)
{
string currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
return currentAction;
}
}
虽然涉及标准URL参数(“controller} / {action} / {id?}”,但一切正常。但是如何读取URL中的变量。
是https://localhost:/Contractors?Status=false
如何获取STATUS数据
附:对于那些后来想要使用Helper的人。 CHTML
<li class="@Html.IsSelected(action: "Index", controller: "Contractors", status: "true")"><a asp-action="Index" asp-controller="Contractors" asp-route-status="true">Clients</a></li>
RouteData
仅包含从路线中提取的值。因此,除非您将status
参数添加到路径(例如/contractors/{status}
),否则无法从路径数据中检索该值。
在这种情况下,它是一个常规的查询字符串参数,您可以从ViewContext.HttpContext.Request
检索:
var status = html.ViewContext.HttpContext.Request.Query["status"].ToString();