如何结合使用asp-all-route-data和查询字符串中的id列表 [英] How to combine usage of asp-all-route-data and a list of ids in query string
问题描述
在ASP.NET中, asp-all-route-data
非常适合将变量传递到锚标记中.但是现在我试图添加一个ID列表,但运气不佳. asp-all-route-data
接受IDictionary< string,string>不能有重复的密钥.但是我需要绑定到诸如?myParams = 1& myParams = 2
之类的查询字符串的列表(由
In ASP.NET, asp-all-route-data
is great for passing variables into an anchor tag. But now I am trying to add a list of ids and not having much luck. asp-all-route-data
accepts an IDictionary<string, string> which cannot have duplicate keys. But I need to bind to a list from query string such as ?myParams=1&myParams=2
(as dictated by ASP.NET out of the box model binding).
var myParams = new List<int> {0,1,2};
var routeData = new Dictionary<string, string>();
foreach (var myParam in myParams)
{
routeData.Add(nameof(myParams), myParam.ToString());
}
我尝试将结果添加到重复的键异常中.
I tried adding results in duplicate key exception.
var myParams = new List<int> {0,1,2};
var routeData = new Dictionary<string, string>();
for (var i = 0; i < myParams.Count; i++)
{
var myParam = myParams[i];
routeData.Add($"{nameof(myParams)}{i}", myParam.ToString());
}
没有模型绑定.
这是完整性的剃刀:
<a asp-route="@routeName" asp-all-route-data="@routeData">click me</a>
推荐答案
在进一步研究该问题的同时,我实际上找到了答案,因此将在此处分享.
While researching the question further I actually found the answer, so will share it here.
事实证明我离我很近,但没有一个命名约定
It turns out I was quite close, but rather than a naming convention of
$"{nameof(myParams)}{i}"
应该是
$"{nameof(myParams)}[{i}]"
var myParams = new List<int> {0,1,2};
var routeData = new Dictionary<string, string>();
for (var i = 0; i < myParams.Count; i++)
{
var myParam = myParams[i];
routeData.Add($"{nameof(myParams)}[{i}]", myParam.ToString());
}
哪个查询字符串(基于我设置的路由)为:
Which results in a query string (based on the route I have set up) of:
?myParams[0]=0&myParams[1]=1&myParams[2]=2
这篇关于如何结合使用asp-all-route-data和查询字符串中的id列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!