【问题标题】:JSON-data to WebMethod using jQuery returning errors使用 jQuery 返回错误的 JSON 数据到 WebMethod
【发布时间】:2015-06-19 08:20:33
【问题描述】:

我正在尝试发送一个 json 列表,其中填充了 'data-seq' 属性中的 id,仅当 'value' == true 时。

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

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
}

【问题讨论】:

  • 我认为你不应该接受它作为字符串,因为你的结构将是一个list,其中包含某种类型的结构,如{"jsonList":[{"id":"1"},{"id":"4"},{"id":"5"},{"id":"7"}]}.. 来自this fiddle的示例
  • 如果您只是发送 ID,为什么不发布字符串列表? ["1","2","3"]
  • 如果我使用 List jsonList 它也不起作用。字符串列表看起来不错,可以举个例子回答一下吗?

标签: c# jquery asp.net ajax json


【解决方案1】:

您只是在发送 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多