Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending complex JSON objects to Asp.net MVC using jQuery

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=...
like image 520
Robert Koritnik Avatar asked Jul 09 '26 06:07

Robert Koritnik


1 Answers

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.

like image 151
Richard Poole Avatar answered Jul 11 '26 19:07

Richard Poole