Sending complex JSON objects to Asp.net MVC using jQuery
ajax, asp.net-mvc-2, jquery
Solution
Have you tried flattening your data?
data = {
"first.Id": 1,
"first.Name": "This is my first name.",
"second.Id": 2,
"second.Name": "The second one."
};
Here's a little jQuery extension to flatten your data:
jQuery.flatten = function(data) {
var flattenFunc = function(flattenedData, flattenFunc, name, value) {
if (typeof(value) == 'object') {
for (var item in value) {
flattenFunc(flattenedData, flattenFunc, name ? name + '.' + item : item, value[item]);
}
}
else {
flattenedData[name] = value;
}
};
var flattenedData = new Array();
flattenFunc(flattenedData, flattenFunc, null, data);
return flattenedData;
};
Simply replace `data` with `$.flatten(data)` in your Ajax request.
Problem
I'm defining an object like: ``` data = { first: { Id: 1, Name: "This is my first name." }, second: { Id: 2, Name: "The second one." } }; ``` Then I'm trying to issue an Ajax request using: ``` $.ajax({ url: "/SomeURL" type: "POST", data: data, success: function(){ ... }, error: function(){ ... } }); ``` But my data gets converted into an array like structure that Asp.net MVC default model binder isn't able to grasp. ``` first[Id]=1&first[Name]=... ``` What should I set or do, so jQuery will correctly convert these into: ``` first.Id=1&first.Name=... ```