2011-07-27 104 views
5

我要香蕉试图找出如何序列化这个(在MVC 3):如何为JSON发布序列化jQuery对象数组?

// 1.我加载的产品阵列中的视图:

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

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

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

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

// 4. LineItem类:

public class LineItem{ 
    public string id {get;set;} 
    public string quantity { get; set; } 
} 

在控制器的功能,所有的值都正确地传递,除了LineItem的列表;它具有正确的元素数量,但id和数量值为null。

我已经把通过提琴手的号召,这是我得到:

[提琴手的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 

[提琴手查询字符串查看]

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 

显然,序列化的字符串和控制器参数不“兼容”。我是不是在视图中正确地格式化产品阵列,还是控制器中的“行项目”列表和类不正确,或两者都是?

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

有人在这?

回答

0

Here是你的答案。看起来你需要在你的动作之上使用一个属性,或者使用一个插件将你的json序列化为默认的模型绑定器可以理解的东西。

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

相关问题