如何为JSON Post序列化jQuery对象数组?

Rad*_*adu 5 arrays model-view-controller jquery serialization object

我要去香蕉试图找出如何序列化这个(在MVC 3中):

// 1.我在视图中加载产品数组:

var products = [];
if (quantity > 0) {                   
    products.push({ 'id': id, 'quantity': quantity });
}
Run Code Online (Sandbox Code Playgroud)

// 2.然后我发布了一堆值,以及产品,如下所示:

$.ajax({
    type: "POST",
    url: '/Orders/Create/',
    data:
    {
        'ShipToPersonId': shipToPersonId,
        'ShipToPersonType': selectedPersonType,
        'ShippingAddressId': shipToAddressId,
        'ShippingInstructions': 'Not yet implemented',
        'LineItems': products,
        'OrderOwnerId': selectedOnBehalfOfPersonId
    },
    dataType: "json",
    success: function (data) {
        alert('Saved: ' + data);
    },
    error: function (data) {
        alert('failed:' + data);
    }
 });
Run Code Online (Sandbox Code Playgroud)

// 3.我的控制器看起来像这样:

 public JsonResult Create(
                           int ShipToPersonId, 
                           string ShipToPersonType, 
                           int ShippingAddressId, 
                           string ShippingInstructions, 
                           List<LineItem> LineItems, 
                           int OrderOwnerId)
    {...}
Run Code Online (Sandbox Code Playgroud)

// 4. LineItem类:

public class LineItem{
    public string id {get;set;}
    public string quantity { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在控制器函数中,除LineItem列表外,所有值都正确传递; 它具有正确的元素数,但id和quantity值为null.

我通过Fiddler打电话,这就是我得到的:

[Fiddler WebForms查看]

=================================
Body                    | Value
========================|========
LineItems[0][id]        | 50
LineItems[0][quantity]  | 10
LineItems[1][id]        | 46
LineItems[1][quantity]  | 20
LineItems[2][id]        | 48
LineItems[2][quantity]  | 30
LineItems[3][id]        | 30
LineItems[3][quantity]  | 50
Run Code Online (Sandbox Code Playgroud)

[Fiddler QueryString查看]

ShipToPersonId=533
&ShipToPersonType=Rep
&ShippingAddressId=517
&ShippingInstructions=Not+yet+implemented
&LineItems%5B0%5D%5Bid%5D=50&LineItems%5B0%5D%5Bquantity%5D=10
&LineItems%5B1%5D%5Bid%5D=46&LineItems%5B1%5D%5Bquantity%5D=20
&LineItems%5B2%5D%5Bid%5D=48&LineItems%5B2%5D%5Bquantity%5D=30
&LineItems%5B3%5D%5Bid%5D=30&LineItems%5B3%5D%5Bquantity%5D=50
&OrderOwnerId=533
Run Code Online (Sandbox Code Playgroud)

显然,序列化字符串和控制器参数不是"兼容的".我没有在视图中正确格式化产品数组,还是控制器中的行项列表和类不正确,或者两者兼而有之?

任何人都可以对此有所了解吗?谢谢!

对此有人吗?

Joh*_*rer 0

是你的答案。看起来您要么需要在操作之上使用一个属性,要么使用一个插件将您的 json 序列化为默认模型绑定程序可以理解的内容。

另外,当您在 ajax 请求中将其设置为数据时,您是否在对象上尝试过 JSON.stringify({'foo', 'bar'}) ?