POST到C#时JSON对象为空

时间:2013-06-12 13:24:24

标签: c# jquery asp.net-mvc asp.net-mvc-4

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; }
}

当我调试时,obj具有children属性,但它始终为null ...在我的浏览器控制台中,它不为空...

1 个答案:

答案 0 :(得分:10)

首先,我建议您将复杂对象从客户端发送到服务器,如JSON:

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

需要注意的事项:

  1. contentType: 'application/json'
  2. data: JSON.stringify(obj)
  3. 客户端上的children属性也必须是数组,而不是属性:

    var obj = {};
    var childObj = {};
    
    childObj.name = 'dominic';
    childObj.age = 22;
    
    obj.children = [];
    obj.children.push(childObj);
    

    或简单地说:

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

    另一个评论:在服务器上,您的Age属性被定义为字符串,而在客户端上,您将其作为整数(age: 22)传递,这是不一致的。除此之外,您不需要将所有C#属性都放在小写中。那真是太可怕了。 JavaScriptSerializer足够智能,可以遵守标准的C#命名约定:

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