asp.net - 将QueryString附加到asp.net核心 anchor 帮助器标签中的href

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

我正在尝试在请求的查询中添加任何内容以 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-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<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/

相关文章:

asp.net - 如何在现有数据库中创建 ASP.Net Identity 表?

javascript - 如何使用 .net 5.0 中下拉列表中的值在 html bootstrap 表中动态插入行?

asp.net-core - 如何简化asp.net core依赖注入(inject)

asp.net-mvc - 如何动态更新 ASP.NET Core View

当部署到 IIS 7.5 上的子目录时,C# Web API 2 应用程序在 GET 方法上生成 404

javascript - 如何使用 Jquery .load() 重新加载部分 View ?

javascript - 在 ASP.NET 的 UserControl 中注册 JavaScript

asp.net - MVC Contrib是否履行了在ASP.NET MVC中提高生产率的 promise

asp.net - 发布到 MVC Controller ,ViewModel 保持为空

c# - 在 Global.Asax - Application_Start 中查找 ASP.NET 应用程序是否在本地运行