Asp.net

將 QueryString 附加到 asp.net core Anchor Helper Tag 中的 href

  • December 5, 2019

我正在嘗試在請求的查詢中添加任何內容到 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>

查詢字元串的附加實際上適用於上述程式碼,但結果中失去了“iron-maiden”和“run-to-the-hills”。上面的標籤助手返回以下內容(注意助手如何將請求中的樂隊和歌曲鏡像到 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-bandasp-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返回類型。

你會像這樣從你的視圖中呼叫它

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

引用自:https://stackoverflow.com/questions/43229707