Append QueryString to href in asp.net core Anchor Helper Tag

夙愿已清 提交于 2019-11-29 14:04:36

There doesn't seem to be any official way to do this yet.

If the @Context.GetRouteData().Values works you should use it instead. The idea behind it is, that GetRouteData gets the current route information from the routing middleware as key value pairs (Dictionary) which should also contain query parameters.

I am not sure if it works in your case and if asp-route-band & asp-route-song are hard-coded or taken from route in your case.

In case that may not work, you could try the following extension method & class:

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;
    }
}

It basically abstracts your code from above behind a extension method and returns a QueryParameters type (which is an extended Dictionary<string,string>) with a single additional method for pure convenience, so you can chain multiple .WithRoute calls, since Add method of dictionary has a void return type.

You'd be calling it from your View like this

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!