POST JSON数组到ASP.NET WebMethod

时间:2016-07-04 00:03:57

标签: asp.net json

我有一个脚本,它按照下面的方式返回JSON中的数据数组。

[
    {"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"

});

我的网络方法看起来像这样

[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 个答案:

答案 0 :(得分: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"

});