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=...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With