2011-07-27 42 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'})?

相關問題