Zer*_*One 7 asp.net asp.net-mvc tag-helpers asp.net-core asp.net-core-tag-helpers
我试图在html结果中向锚点添加请求查询中的任何内容:
虚构的例子:
用户发出请求(请注意,乐队和歌曲可以是任何内容,我有一条路径来满足此请求:模板:"{band}/{song}"):
http://mydomain/band/song?Param1=111&Param2=222
Run Code Online (Sandbox Code Playgroud)
现在我希望我的锚点将查询字符串部分附加到我的锚点的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>
Run Code Online (Sandbox Code Playgroud)
查询字符串的附加实际上与上面的代码一起使用,但随后结果中丢失了"铁娘子"和"跑到山上".上面的标签助手返回以下内容(注意帮助器如何将请求中的乐队和歌曲镜像到href中,而不是我在asp-route属性中指定的乐队和歌曲):
<a href="http://mydomain/band/song?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>
Run Code Online (Sandbox Code Playgroud)
我希望帮助者得到以下结果:
<a href="http://mydomain/iron-maiden/run-to-the-hills?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>
Run Code Online (Sandbox Code Playgroud)
看起来当我使用asp-all-route-data时,我在结果中丢失了asp-route-band和asp-route-song值.
有没有人偶然发现了这个?
谢谢
Hooroo
似乎还没有任何官方方法可以做到这一点。
如果@Context.GetRouteData().Values
可行,您应该改用它。其背后的想法是,GetRouteData
从路由中间件获取当前路由信息作为键值对(字典),其中还应包含查询参数。
我不确定它是否适用于您的情况以及asp-route-band
&asp-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)
{
Add(routeParam, routeValue);
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,它从上面在扩展方法后面抽象了您的代码,并返回一个带有单个附加方法的QueryParameters
类型(扩展为Dictionary<string,string>
),以提供纯粹的便利,因此您可以链接多个.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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1645 次 |
最近记录: |