dudemonkey
dudemonkey

Reputation: 1100

Passing List of objects via querystring to MVC Controller

I've got a situation where I need to pass a List of objects to an MVC Controller, but I'm not sure how to format this in the querystring. The reason I would want to do this is because this is not a web application, it's a web service that accepts data via the querystring and routes it to a controller that does the work.

So, given a class called MyParam with properties A & B, how can I construct a querystring that will pass data to the following controller method:

public ActionResult MyMethod(List<MyParam> ParamList)

I've tried using the MVC framework to RedirectToAction and RedirectToResult to see what it comes up with, but I assume that my n00bness with MVC is causing me to make a mistake because it never passes the data correctly and MyMethod always has null for the parameter.

Thanks in advance!

Upvotes: 11

Views: 16890

Answers (3)

Jonathan Kaufman
Jonathan Kaufman

Reputation: 314

Ok, based on the information provided I don't think you want what you think you want. In your case on the client you POST the data to the controller. Not use a querystring.

ok since you have to use querystring. my new answer: serialize object, convert it to base64 string and pass it, then convert it back.

Upvotes: 0

Tejs
Tejs

Reputation: 41236

I've found that the JsonValueProvider works much better than the normal ValueProvider for binding to a list. Simply convert your data to a JSON object like so:

<YourRoute>?ParamList=[{SomeProperty:'Value'},{SomeProperty:'Value'}];

And the JsonValueProvider will take care of the rest. This is assuming you have the ability to say "post this data as Json".

I also disclaim whether or not this would be a good idea.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

You may find the following blog post useful for the wire format of lists you need to use if you want the default model binder to successfully parse the request into a strongly typed array of objects. Example of query string:

[0].Title=foo&[0].Author=bar&[1].Title=baz&[1].Author=pub...

where:

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
}

will successfully bind to:

public ActionResult MyMethod(IEnumerable<Book> books) { ... }

Upvotes: 14

Related Questions