【问题标题】:asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'asp.net json web服务发送数组错误无法将'System.String'类型的对象转换为'System.Collections.Generic.List`1 [System.String]'类型
【发布时间】:2013-08-15 01:13:01
【问题描述】:

我想使用 ajax 和 webservice 将数据从 JavaScript 插入数据库, 我有一些控件,我通过 jQuery 获取它们的值并将它们的值组成一个数组。

当我发送数组时会导致此错误:

无法将“System.String”类型的对象转换为“System.Collections.Generic.List1[System.String]”类型的对象

var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
    variables[i] = $(this).find('.selected').find(".text").html();
    i++;
});

$.ajax({
    type: 'post',
    data: "{ 'a':'" +variables + "'}",
    dataType: 'json',
    url: 'HomeWebService.asmx/insertAd',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

        alert("data : " + data.d);
    }
});

这是 C# 代码

[WebMethod]
public object insertAd(List<string> a)
{
    return a;
}

【问题讨论】:

  • data: "{ 'a':'" +variables + "'}" 发送一个包含Object 或类似内容的字符串。
  • @MelanciaUK 但它们都是跨度的文本
  • 对不起。我的错。我正在发布答案。

标签: c# jquery asp.net ajax


【解决方案1】:

您需要像这样将$.ajax 调用的data 参数设为:JSON.stringify({'a': variables})

JSON 变量在 JSON 实现,就像答案here 中提到的那样

另外,success 函数中有一个额外的 }

因此,将来,如果您想为传递给 Web 服务的数据对象添加额外的参数,您可以像这样构造它:

var someArr = ['el1', 'el2'];

JSON.stringify({ 
  'param1': 1,
  'param2': 'two'
  'param3': someArr
  // etc
});

JavaScript:

var variables = Array();

var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {

  variables[i] = $(this).find('.selected').find(".text").html();

  i++;
});



$.ajax({
    type: 'post',
    data: JSON.stringify({'a': variables}),
    dataType: 'json',
    url: 'HomeWebService.asmx/insertAd',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

      alert("data : " + data.d);
    });

});

C#

[WebMethod]
public object insertAd(List<string> a)
{
  return a;
}

【讨论】:

    【解决方案2】:

    试试这个

                data: JSON.stringify({ 'a': variables }),
    

    【讨论】:

      【解决方案3】:

      data:要发送到服务器的数据。如果还不是字符串,则将其转换为查询字符串。它附加到 GET 请求的 url。请参阅 processData 选项以防止此自动处理。对象必须是键/值对。如果 value 是一个 Array,jQuery 会根据传统设置的 value 序列化多个具有相同 key 的值。

      所以,尝试在你的 ajax 调用中添加一个新参数:

      $.ajax({
          type: 'post',
          data: { 'a': variables }, // Notice some changes here
          dataType: 'json',
          traditional: true, // Your new parameter
          url: 'HomeWebService.asmx/insertAd',
          contentType: 'application/json; charset=utf-8',
          success: function (data) {
              alert("data : " + data.d);
          }
      });
      

      试试这个方法。也许您需要更改 Web 服务方法以期望 array 而不是 List,但我不确定。

      【讨论】:

        猜你喜欢
        • 2014-03-14
        • 2022-08-09
        • 2017-11-24
        • 2012-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        相关资源
        最近更新 更多