加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

将QueryString附加到asp.net核心Anchor Helper Tag中的href

发布时间:2020-12-16 06:55:33 所属栏目:asp.Net 来源:网络整理
导读:我试图在html结果中向锚点添加请求查询中的任何内容: 虚构的例子: 用户发出请求(请注意,乐队和歌曲可以是任何内容,我有一条路径来满足此请求:模板:“{band} / {song}”): http://mydomain/band/song?Param1=111Param2=222 现在我希望我的锚点将查询字符
我试图在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>

查询字符串的附加实际上与上面的代码一起使用,但随后结果中丢失了“铁娘子”和“跑到山上”.上面的标签助手返回以下内容(注意帮助器如何将请求中的乐队和歌曲镜像到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值.

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

谢谢

Hooroo

解决方法

似乎没有任何官方方式来做到这一点.

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

我不确定它是否适合你的情况,如果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;
    }
}

它基本上从扩展方法后面抽象你的代码并返回一个QueryParameters类型(这是一个扩展的Dictionary< string,string>),带有一个额外的方法,为了方便起见,所以你可以链接多个.WithRoute调用,因为Add方法dictionary有一个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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读