Reputation: 4405
I have an action method that looks like this:
public ActionResult DoSomething(string par, IEnumerable<string> mystrings)
I wanted to map this to a URL using Url.Action, passing mystrings in the RouteValueDictionary. However, this only yields a query string that only corresponds to mystrings.ToString().
How could I pass a list in the query string? Is there some functionality in MVC 2 that supports this?
CLARIFICATION: The action method is called using GET, not POST.
There is no problem for my action method to parse the query string DoSomething?mystrings=aaa&mystrings=bbb
However, I cannot generate this using Url.Action. Passing a list generates the following query string: mystrings=system.collections.generic.list%601%5bsystem.string%5d
Is there some way I could accomplish this easily?
Upvotes: 4
Views: 7679
Reputation: 199
public static class Extensions
{
public static string ToQueryString(this IEnumerable<string> items)
{
if (items.Count>0)
{
var urlParam = string.Join("&", items.ToArray());
return "?"+ urlParam;
}
return "";
}
}
Upvotes: 0
Reputation: 14677
EDIT: Ok, now I see where you're going with this. I don't think ASP.NET MVC has that built-in since it's designed to generate query strings from route values that have unique names. You may have to roll your own. I would create an extension method on IEnumerable<String>
like this:
public static class Extensions
{
public static string ToQueryString(this IEnumerable<string> items)
{
return items.Aggregate("", (curr, next) => curr + "mystring=" + next + "&");
}
}
Then you could generate your own query string like this:
<%= Url.Action("DoSomething?" + Model.Data.ToQueryString()) %>
This needs some polish as you should UrlEncode your strings and it creates a trailing "&", but this should give you the basic idea.
Upvotes: 2
Reputation: 1038780
How about:
<%: Html.ActionLink("foo", "DoSomething", new RouteValueDictionary() {
{ "mystrings[0]", "aaa" }, { "mystrings[1]", "bbb" }
}) %>
which generates:
<a href="/Home/DoSomething?mystrings%5B0%5D=aaa&mystrings%5B1%5D=bbb">foo</a>
This is not exactly the URL you were looking for but it will successfully bind to your controller action. If you want to generate an url without the square brackets you will need to roll your own helper method.
Upvotes: 1