How can I use Url.Action with list parameters?
Instead of using an Anonymous Type, build a RouteValueDictionary
. Format the parameters as parameter[index]
.
@{
var categories = new List<int>() { 6, 7 };
var parameters = new RouteValueDictionary();
for (int i = 0; i < categories.Count; ++i)
{
parameters.Add("category[" + i + "]", categories[i]);
}
}
Then,
@Url.Action("Test", parameters)
Build the querystring yourself, it's evident that UrlHelper was not designed for this use case.
Using:
static class QueryStringBuilder {
public static string ToQueryString(this NameValueCollection qs) {
return ToQueryString(qs, includeDelimiter: false);
}
public static string ToQueryString(this NameValueCollection qs, bool includeDelimiter) {
var sb = new StringBuilder();
for (int i = 0; i < qs.AllKeys.Length; i++) {
string key = qs.AllKeys[i];
string[] values = qs.GetValues(key);
if (values != null) {
for (int j = 0; j < values.Length; j++) {
if (sb.Length > 0)
sb.Append('&');
sb.Append(HttpUtility.UrlEncode(key))
.Append('=')
.Append(HttpUtility.UrlEncode(values[j]));
}
}
}
if (includeDelimiter && sb.Length > 0)
sb.Insert(0, '?');
return sb.ToString();
}
}
You can write this:
var parameters = new NameValueCollection {
{ "category", "1" },
{ "category", "2" }
};
var url = Url.Action("Search") + parameters.ToQueryString(includeDelimiter: true);