[英]Append QueryString to href in asp.net core Anchor Helper Tag
我正在嘗試在 html 結果中的錨點的請求查詢中添加任何內容:
虛構示例:
用戶提出請求(請注意,樂隊和歌曲可以是任何東西,我有一條滿足此請求的路線:模板:“{band}/{song}”):
http://mydomain/band/song?Param1=111&Param2=222
現在我希望我的錨點到 append 查詢字符串部分到我的錨點的 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>
查詢字符串的 append 實際上適用於上述代碼,但結果中丟失了“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-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
返回類型。
你會像這樣從你的視圖中調用它
<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-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())"
在使用“asp-all-route-data”保存查詢參數后,您的自定義參數被刪除,只需將您的參數移動到“asp-all-route-data”之后,一切都會如您所願
asp-all-route-data="@Context.Request.Query.ToDictionary(d=>d.Key,d=>d.Value.ToString()) asp-route-band="iron-maiden" asp-route-song="run-to-the-hills"
這將返回您期望的鏈接
<a href="http://mydomain/iron-maiden/run-to-the-hills?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.