Reputation: 12580
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());
}
results in no model binding.
Here's the razor for completeness:
<a asp-route="@routeName" asp-all-route-data="@routeData">click me</a>
Upvotes: 3
Views: 1187
Reputation: 12580
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}"
It should have been
$"{nameof(myParams)}[{i}]"
as detailed in the Microsoft documentation for model binding.
Full code example:
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
Upvotes: 4