Having issues getting ASP.NET MVC3 to bind my complex JSON object that contains a list.
Here's the structure I have for my objects.
public class PageModel
{
public PageModel() { }
public CustomObject1 CustomObject { get; set; }
public IEnumerable<CustomObject2> Objects { get; set; }
}
public class CustomObject1
{
public CustomObject1() { }
[Required]
public int CustomId1 { get; set; }
public string CustomName { get; set; }
}
public class CustomObject2
{
public CustomObject2() { }
[Required]
public int Custom2Id { get; set; }
public CustomObject3 SubItem { get; set; }
public int SubItemId { get; set; }
}
You can assume CustomObject3
is of similar structure - no need to duplicate yet another made up class, so I figure you can use your imagination :)
Here's the Javascript/Jquery that makes the POST call (assume all the JS leading up to this provides the correct data):
//$obj1 has all data for the first object
var firstObj = { };
firstObj.CustomId1 = $obj1.Id;
firstObj.CustomName = $obj1.Name;
var i = 0;
//$objects is an array with all the data
$.each($objects, function() {
objsArray[i] = {
Custom2Id: $(this).Id,
SubItemId: $(this).itemId
};
++i;
});
$.ajax({
type: 'POST',
url: '/Action/Method',
data: { CustomObject: firstObj, Objects: objsArray },
//Success/error handlers here
});
And finally (I know, quite some code) here's an overview of the method I have:
public class ActionController : Controller {
public JsonResult Method(PageModel model) {
//Gets here - model.CustomObject is filled correctly, and model.Objects has a correct count of whatever data I passed to the method - but all of the properties are empty!
}
}
As I said, the first object is filled and all of the data is there when I debug and step through. If I pass two objects in the Objects
array in the JSON object, I see a Count
of 2 in the controller, but Custom2Id
and SubItemId
are empty. What gives?
When I specify a contentType
of 'application/json'
in my $.ajax
call, MVC complains about the data being passed. Also tried splitting the model
parameter in the MVC method into two separate parameters, but it does not help.
Any help is greatly appreciated - this one has me stumped!