【问题标题】:Read URL parameter for Helpers读取 Helpers 的 URL 参数
【发布时间】:2023-03-11 09:02:01
【问题描述】:

有 Helpers 负责将 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

如何获取状态数据

附:对于那些以后想使用 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>

【问题讨论】:

    标签: c# asp.net-core asp.net-core-2.0


    【解决方案1】:

    RouteData 仅包含从路由中提取的值。因此,除非您将 status 参数添加到路由(例如 /contractors/{status}),否则您无法从路由数据中检索值。

    在这种情况下,它是一个常规的查询字符串参数,您可以从 ViewContext.HttpContext.Request 中检索它:

    var status = html.ViewContext.HttpContext.Request.Query["status"].ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2015-06-07
      • 1970-01-01
      • 2016-05-22
      • 2015-03-19
      • 2011-11-12
      相关资源
      最近更新 更多