views:

141

answers:

2

Hi,

I'm trying to use the jquery ajax function to post to a MVC2 controller action, but my parameters include an array of a (simple) custom class and the action is not getting the data correctly.

Client:

var element1 = { FirstName: 'Raymond', LastName: 'Burr' };
var element2 = { FirstName: 'Johnny', LastName: 'Five' };
var var2 = [element1, element2]; 
var var1 = 'some string';    
var parms = {
  var1: var1,
  var2: var2
};
var ajaxArgs = {
    type: "POST",
    traditional: true,
    url: "/Home/Test1",
    data: parms,
    dataType: "json",
    success: returnSuccess,
    error: returnError
};

$.ajax(ajaxArgs);

Server:

[HttpPost]                                                                   
public ActionResult Test1(string var1, List<TestParameterClass> var2) { ... }

public class TestParameterClass              
{                                        
  public string FirstName { get; set; }
  public string LastName { get; set; } 
}

2 cases which already work: 1) Using a List<_string> as action parameter and changing the javascript array to a string array.
2) Using a TestParameterClass as an action parameter and passing 1 instance of the custom class.

So the real trick seems to be getting an array of a custom class passed successfully and with other flat (string) parameters.

Any ideas to make this work? Also is there any documentation on how MVC2 translates the parameter to some C# type (I've used List<> only b/c it seems the most widely used)?

Thanks!

A: 

Ah, the Model Binder. The source of so much magic and the cause of so much woe when it comes to .NET MVC. The Model Binder is what turns parameters into objects, and sometimes it's a little picky about what you pass it.

In this particular case, I think what you want is to pass parameters in the form

"people[0].FirstName": "Raymond",
"people[0].LastName": "Burr",
"people[1].FirstName": "Johnny",
"people[1].LastName": "Five"

Basically, if you're passing the model binder a collection type, it wants the parameters to be named with array-style indices (bracket-number) and then the property name. At least that's what's worked for me; I'm no MVC ninja.

eliah
A: 

I would try figure out if the AJAX call is wrong or if the input model binding on the server is wrong. Use Firebug or Fiddler to inspect the AJAX call and specifically the POST data. if it looks correct, then the problem is likely in the model binding.

check out this post for some "documentation" of the list parsing: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

another thing to try is to create a sample page with a form that mimics that data you're passing in via AJAX. if you can get the form to POST and model bind correctly, chances are your AJAX call will work as well.

dave thieben