我正在尝试在请求的查询中添加任何内容以 anchor 定html结果:
虚构的例子:
用户发出请求(请注意,乐队和歌曲可以是任何东西,我有一条路线可以满足此请求:模板:“{band}/{song}”):
http://mydomain/band/song?Param1=111&Param2=222
现在,我希望 anchor 将查询字符串部分附加到 anchor 的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>
查询字符串的附加内容实际上与以上代码一起使用,但是结果中丢失了“铁娘子”和“奔向山坡”。上面的标签帮助程序返回以下内容(请注意该帮助程序如何将请求中的乐队和歌曲镜像到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-band 和 asp-route-song 值。
有没有人偶然发现过这个?
谢谢
胡鲁
最佳答案
似乎还没有任何官方方法可以做到这一点。
如果@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)
{
this[routeParam] = routeValue;
return this;
}
}
基本上,它从上面在扩展方法后面抽象代码,并返回
QueryParameters
类型(它是扩展的Dictionary<string,string>
)和一个附加方法,以提供纯粹的便利,因此您可以链接多个.WithRoute
调用,因为字典的Add
方法具有void
返回类型。您可能会这样从 View 中调用它
<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>
关于asp.net - 将QueryString附加到asp.net核心 anchor 帮助器标签中的href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229707/