2016-07-04 68 views
0

我有一個腳本,它返回JSON中的數據數組,如下所示。POST JSON數組到ASP.NET WebMethod

[ 
    {"ItemID":"10319","ItemCode":"ITEM-010318","Qty":"1","custRef":"12 - Mitsubishi Fighter FK61F"}, 
    {"ItemID":"10933","ItemCode":"ITEM-010932","Qty":"1","custRef":"12 - Mitsubishi Fighter FK61F"},{"ItemID":"10537","ItemCode":"ITEM-010536","Qty":"1","custRef":"12 - Mitsubishi Fighter FK61F"}, 
    {"ItemID":"14863","ItemCode":"ITEM-014862","Qty":"1","custRef":"12 - Mitsubishi Fighter FK61F"}, 
    {"ItemID":"14864","ItemCode":"ITEM-014863","Qty":"1","custRef":"12 - Mitsubishi Fighter FK61F"} 
] 

此數據存儲在一個名爲cartData

我然後將數據推到通過AJAX我的WebMethod變量,如下所示

$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "OrderFormServices.asmx/AddItemsToCart", 
    data: JSON.stringify(cartData), 
    dataType: "json" 

}); 

我的Web方法看起來像這樣

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public void AddItemsToCart(string [] itemID, string [] itemCode, string [] Qty, string [] custRef) 

但是,當我嘗試和POST數據時,控制檯上出現錯誤我無法做到頭或尾!任何人都可以點亮它嗎?

Type 'System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, 
Culture=neutral, PublicKeyToken=b77a5c561934e089], 
[System.Object, mscorlib, 
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 
is not supported for deserialization of an array. 

回答

1

該方法需要每個字段的數組。 所以,要麼你改變的方法是這樣的:

public void AddItemsToCart(CartItem[] items) 

哪裏CartItem是類所有這些領域。

OR

編輯JS通過作爲Web方法預期一樣:

var data = { 
itemID : [], 
itemCode:[], 
Qty:[], 
custRef:[]}; 
//here fill all array with each one of the items in the json array. 
$.ajax({ 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "OrderFormServices.asmx/AddItemsToCart", 
    data: JSON.stringify(data), 
    dataType: "json" 

}); 
+0

謝謝,我已經編輯按你的第二個建議,現在我使用 'cartData.push( { 'ITEMID':itemIdVal, 'itemCode':itemCodeVal, '數量':qtyVal, 'custRef':custRefVal });'然而這似乎並不奏效 - cartData.push不是一個函數? –

+0

這不會工作,它會這樣工作: cartData.push({'itemID':[itemIdVal],'itemCode':[itemCodeVal],'qty':[qtyVal],'custRef':[custRefVal]} ); 也要確保param的名稱與web方法相同,例如:數量。 – MoustafaS

+0

我得到'cartData.push'不是一個函數嗎? –