简体   繁体   English

POST到C#时JSON对象为空

[英]JSON Object Empty On POST to C#

jQuery: 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): 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... 当我调试时, obj有一个children属性,但它总是为null ...在我的浏览器控制台中,它不是null ...

First I would recommend you sending complex objects from the client to the server as JSON: 首先,我建议您将复杂对象从客户端发送到服务器作为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: 此外,客户端上的children属性必须是数组,而不是属性:

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. 另一个注释:在服务器上,您的Age属性被定义为字符串,而在客户端上,您将其作为整数( age: 22 )传递,这是不一致的。 In addition to that you don't need to put all your C# properties in lowercase. 除此之外,您不需要将所有C#属性都放在小写中。 That's just horrible. 那太可怕了。 The JavaScriptSerializer is intelligent enough to respect the standard C# naming convention: JavaScriptSerializer足够智能,可以遵守标准的C#命名约定:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM