使用jQuery返回错误的JSON数据到WebMethod

时间:2015-06-19 08:20:34

标签: c# jquery asp.net ajax json

我尝试发送一个json列表,其中填入了来自" data-seq'属性仅限于'值' == true。

我已经尝试了很多解决方案,但它不断给我发错误消息,最常见的是"类型字符串没有无参数构造函数"当使用string []或&#34时,不支持字符串反序列化数组"在WebMethod中使用string作为代码隐藏参数时。

function sentData() {        
    var json = [];
    $('.btn[value="true"]').each(function () {
        var obj = {
            id: $(this).attr("data-seq")
        };
        json.push(obj);
    });
    json = JSON.stringify({ jsonList: json });
    console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)

    $.ajax({
        type: "POST",
        async: true,
        url: "Default.aspx/getList",
        dataType: "json",
        data: json,
        contentType: "application/json; charset=utf-8",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
        },
        success: function(json){
            //do something with the result
        }
    });
    return false;
}

// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
    // string: string is not supported for deserialization of an array
    // string[]: there is no parameterless constructor for the type string
}

1 个答案:

答案 0 :(得分:0)

您只是发送ID,因此请将它们发送为逗号分隔的字符串,如下所示:

function sentData() {        
    var json = [];
    $('.btn[value="true"]').each(function () {
        var id = $(this).attr("data-seq")
        json.push(id);
    });

    $.ajax({
        type: "POST",
        async: true,
        url: "Default.aspx/getList",
        dataType: "json",
        data: '{jsonList: "' + json + '" }',
        contentType: "application/json; charset=utf-8",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
        },
        success: function(json){
            //do something with the result
        }
    });
    return false;
}

代码背后:

[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
    List<string> ListOfIDs = jsonList.Split(',').ToList();
}