Using List as Query String Parameter Using MVC

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 to a RouteValueDictionary. However, this only gives a query string that matches only mystrings.ToString ().

How can I pass the list in the query string? Is there any functionality in MVC 2 that supports this?

ACKNOWLEDGMENT: the action method is invoked using GET, not POST.

No problem for my action method for parsing a DoSomething query string? mystrings = aaa & mystrings = bbb

However, I cannot generate this using Url.Action. List passing generates the following query string: mystrings = system.collections.generic.list% 601% 5bsystem.string% 5d

Is there any way to make this easy?

+4
source share
2 answers

Yes. binding model to list

EDIT: Okay, now I see where you are going with this. I do not think that ASP.NET MVC has a built-in interface, since it is designed to generate query strings from route values ​​that have unique names. You may need to collapse yourself. I would create an extension method on IEnumerable<String> as follows:

 public static class Extensions { public static string ToQueryString(this IEnumerable<string> items) { return items.Aggregate("", (curr, next) => curr + "mystring=" + next + "&"); } } 

Then you can create your own query string as follows:

 <%= Url.Action("DoSomething?" + Model.Data.ToQueryString()) %> 

This requires several paints, since you need UrlEncode your lines, and it creates the final "&", but this should give you the basic idea.

+2
source

What 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 the URL you were looking for, but it will be successfully bound to your controller action. If you want to create a URL without square brackets, you will need to collapse your own helper method.

+1
source

All Articles