views:

38

answers:

2

Hi. 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?

+1  A: 

Yes. Model Binding To A List

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.

Patrick Steele
@Patrick Well, that seems to pertain only to POST model binding, which I have used before. However, this is about GET model binding and the query string. I will update my question to clarify.
Max Malmgren
Patrick Steele
@Patrick Well, I can successfully CALL the method. Which is pretty logical, since its the same for POST. However, I cannot generate these query strings. I'd like to use Url.Action, but it does not work out of the box, the way I am trying to. Please see my updated question (Again) ;)
Max Malmgren
A: 

How about:

<%: Html.ActionLink("foo", "DoSomething", new RouteValueDictionary() { 
    { "mystrings[0]", "aaa" }, { "mystrings[1]", "bbb" } 
}) %>

which generates:

<a href="/Home/DoSomething?mystrings%5B0%5D=aaa&amp;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.

Darin Dimitrov