user1477388
user1477388

Reputation: 21430

JSON Object Empty On POST to C#

jQuery:

$('#test').click(function () {

    var obj = new Object();
    var childObj = new Object();

    childObj.name = 'dominic';
    childObj.age = 22;

    obj.children = new Object ({ child : childObj });

    console.log(obj);

    $.ajax({
        url: '@Url.Action("Test")',
        type: 'POST',
        data: obj,
        dataType: 'json',
        success: function (msg) {
            //console.log(msg.status);
        }
    });

});

C# (MVC 4):

public JsonResult Test(testObj obj)
{
    foreach (childObj child in obj.children)
    {
        Debug.Print(child.name);
        Debug.Print(child.age);
    }

    return Json(null);
}

public class testObj
{
    public List<childObj> children { get; set; }
}

public class childObj
{
    public string name { get; set; }
    public string age { get; set; }
}

When I debug, obj has a children property, but it is always null... In my browser console, it is not null...

Upvotes: 3

Views: 4228

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

First I would recommend you sending complex objects from the client to the server as JSON:

$.ajax({
    url: '@Url.Action("Test")',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(obj),
    dataType: 'json',
    success: function (msg) {
        //console.log(msg.status);
    }
});

Things to notice:

  1. contentType: 'application/json'
  2. data: JSON.stringify(obj)

Also your children property on the client must be an array, not a property:

var obj = {};
var childObj = {};

childObj.name = 'dominic';
childObj.age = 22;

obj.children = [];
obj.children.push(childObj);

or simply:

var obj = {
    children: [
        { name: 'dominic', age: 22 }
    ]
};

Another remark: On the server your Age property is defined as string whereas on the client you are passing it as integer (age: 22) which is inconsistent. In addition to that you don't need to put all your C# properties in lowercase. That's just horrible. The JavaScriptSerializer is intelligent enough to respect the standard C# naming convention:

public class TestObj
{
    public List<ChildObj> Children { get; set; }
}

public class ChildObj
{
    public string Name { get; set; }
    public string Age { get; set; }
}

Upvotes: 10

Related Questions