本文介绍了如何结合使用 asp-all-route-data 和查询字符串中的 id 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET 中,asp-all-route-data 非常适合将变量传递到锚标记中.但现在我正在尝试添加一个 id 列表,但运气不佳.asp-all-route-data 接受一个 IDictionary不能有重复的键.但我需要从查询字符串绑定到一个列表,例如 ?myParams=1&myParams=2(如 ASP.NET 开箱即用的模型绑定).

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}]"

有关模型绑定的 Microsoft 文档.

完整代码示例:

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 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:12