3

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属性,但它始终为空......在我的浏览器控制台中,它不为空......

4

1 回答 1

11

首先,我建议您将复杂对象以 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)

此外,您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; }
}
于 2013-06-12T13:28:03.493 回答