Reputation: 1706
I have been looking around and I have not found a solution as of yet. If I have some JSON with nested objects that I post to my controller, how can I get it to bind to the object correctly. My code works perfectly for any objects that do not have any form of nesting. Solution, anyone?
var object = { "RandomString": "ASDFASDF" };
var nestedobject = { "AnotherString": "ASDFASDF", "Object": object };
$.ajax({
type: 'POST',
url: 'Controller/Method',
data: nestedobject,
dataType: 'json',
success: callback
});
Upvotes: 2
Views: 1263
Reputation: 82335
It should be perfect with the deserialization of nested objects as long as the server knows about the types...
If you are using the JsonValueProviderFactory
for MVC3 you have to make sure you JSONify the data you are passing and use the appropriate content type like below...
The default behavior for jQuery when passing an object to data
for a $.ajax
call is to create a KVP for the object, which is likely more suited for standard form submission or querystring values, that is why you have to JSON.stringify
the data.
var o = { "RandomString": "ASDFASDF" };
var nestedobject = { "AnotherString": "ASDFASDF", "SomeObject": o };
$.ajax({
type: 'POST',
url: 'Controller/Method',
data: JSON.stringify(nestedobject),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: callback
});
Using that the JsonValueProviderFactory should deserialize the parameters correctly and map to a controller action signature like below..
public ActionResult Method(string AnotherString, SomeType SomeObject) { /* ... */ }
public class SomeType {
public string RandomString {get;set;}
}
I wanted to put this here for completeness sake. I used the code he gave me but the main issue is I needed to mark the object with the SerializableAttribute
. Thanks!
Upvotes: 1