【问题标题】:Append QueryString to href in asp.net core Anchor Helper Tag将 QueryString 附加到 asp.net core Anchor Helper Tag 中的 href
【发布时间】:2017-08-30 23:31:54
【问题描述】:

我正在尝试将请求查询中的任何内容添加到 html 结果中的锚点:

虚构的例子:

用户提出请求(请注意,乐队和歌曲可以是任何东西,我有一条满足此请求的路线:模板:“{band}/{song}”):

http://mydomain/band/song?Param1=111&Param2=222

现在我希望我的锚将查询字符串部分附加到我的锚的 href 中。所以我尝试了这样的事情(注意'asp-all-route-data'):

<a asp-controller="topic" asp-action="topic" asp-route-band="iron-maiden" asp-route-song="run-to-the-hills" asp-all-route-data="@Context.Request.Query.ToDictionary(d=>d.Key,d=>d.Value.ToString())">Iron Maiden - Run to the hills</a>

查询字符串的追加实际上适用于上述代码,但结果中丢失了“iron-maiden”和“run-to-the-hills”。上面的标签助手返回以下内容(注意助手如何将请求中的乐队和歌曲镜像到 href 中,而不是我在 asp-route 属性中指定的乐队和歌曲):

<a href="http://mydomain/band/song?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>

我希望助手会得到以下结果:

<a href="http://mydomain/iron-maiden/run-to-the-hills?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>

似乎当我使用 asp-all-route-data 时,我失去了 asp-route-bandasp-route-song 结果中的值。

有没有人偶然发现过这个?

谢谢

呵呵

【问题讨论】:

  • 似乎没有任何官方方式,但我可能有一个解决方法的想法,但首先:@Context.GetRouteData().Values 工作吗? GetRouteData 从路由中间件获取路由作为键值对,还应该包含查询参数。不确定它是否适用于您的情况,以及 asp-route-band 和 asp-route-song 是硬编码还是从您的情况下取自路由

标签: asp.net asp.net-mvc asp.net-core tag-helpers asp.net-core-tag-helpers


【解决方案1】:

似乎还没有任何官方方法可以做到这一点。

如果@Context.GetRouteData().Values 有效,您应该改用它。其背后的想法是,GetRouteData 从路由中间件获取当前路由信息作为键值对(字典),其中还应包含查询参数。

我不确定它是否适用于您的情况,以及 asp-route-bandasp-route-song 在您的情况下是否是硬编码或取自路线。

如果可能不起作用,您可以尝试以下扩展方法和类:

public static class QueryParamsExtensions
{
    public static QueryParameters GetQueryParameters(this HttpContext context)
    {
        var dictionary = context.Request.Query.ToDictionary(d => d.Key, d => d.Value.ToString());
        return new QueryParameters(dictionary);
    }
}

public class QueryParameters : Dictionary<string, string>
{
    public QueryParameters() : base() { }
    public QueryParameters(int capacity) : base(capacity) { }
    public QueryParameters(IDictionary<string, string> dictionary) : base(dictionary) { }

    public QueryParameters WithRoute(string routeParam, string routeValue)
    {
        this[routeParam] = routeValue;

        return this;
    }
}

它基本上从扩展方法后面抽象您的代码并返回一个 QueryParameters 类型(这是一个扩展 Dictionary&lt;string,string&gt;)和一个额外的方法,纯粹是为了方便,所以你可以链接多个 .WithRoute 调用,因为Add 字典方法有一个 void 返回类型。

你会像这样从你的视图中调用它

<a  asp-controller="topic"
    asp-action="topic" 
    asp-all-route-data="@Context.GetQueryParameters().WithRoute("band", "iron-maiden").WithRoute("song", "run-to-the-hills");"
>
    Iron Maiden - Run to the hills
</a>

【讨论】:

  • 嘿,谢谢。非常优雅的解决方案。我确实在 WithRoute 方法中做了一个小改动:if (this.ContainsKey(routeParam)) this[routeParam] = routeValue;否则添加(路由参数,路由值);
  • 哦,顺便说一句。 @Context.GetRouteData().Values 不包含任何查询参数
  • 我必须添加一个检查以防止重复键 WithRoute() 方法:if(!ContainsKey(routeParam))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2017-07-05
相关资源
最近更新 更多