将参数传递给jQuery ajax调用ASP.NET webmethod

lar*_*ers 10 jquery json webforms asp.net-ajax

我知道有更多的线索,但他们不帮助我,我在这里疯了!

我想使用jQuery Ajax将一些参数传递给Web方法.

var paramList = '';
for(i = 0; i < IDList.length; i++){
    if (paramList.length > 0) paramList += ',';  
        paramList += '"' + 'id' + '":"' + IDList[i].value + '"';  
    }
    paramList = '{' + paramList + '}';  
    var jsonParams = JSON.stringify(paramList);


    $.ajax({
        type: "POST",          
        url: "editactivity.aspx/UpdateSequenceNumber",          
        data: jsonParams,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {

        }
    });
Run Code Online (Sandbox Code Playgroud)

在ajax调用中,如果我将数据放入paramList,我会收到错误:"无效的Web服务调用,缺少参数值:\ u0027a\u0027."

如果我把数据放到jsonParams我得到错误:

"无法将类型为\ u0027System.String\u0027的对象转换为类型\ u0027System.Collections.Generic.IDictionary`2 [System.String,System.Object]\u0027"

如果我写出来paramList,那就是正确的JSON格式{"id":"140", "id":"138"}

如果我写出来jsonParams,它的格式不正确"{\"id\":\"140\",\"id\":\"138\"}"

网络方法:(它还没那么多......)

[System.Web.Services.WebMethod]
    public static string UpdateSequenceNumber(string a, string b)
    {
         return a+b;
    }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?似乎无法让这个JSON正确.

更新:

在第一个答案的一些帮助后,我现在发送{"id":["138","140"]}AJAX请求.

web方法现在采用一个名为id参数的字符串.

[System.Web.Services.WebMethod]
public static string UpdateSequenceNumber(string id)
{
     return id;
}
Run Code Online (Sandbox Code Playgroud)

现在我收到了新的错误:

"对阵列的反序列化不支持类型\ u0027System.Array\u0027."

Ahm*_*ıcı 15

您的json参数名称必须与c#参数名称相同.

{"a":"140", "b":"138"}
Run Code Online (Sandbox Code Playgroud)

如果要向服务器发送未知数量的参数,则可以在客户端将其连接到一个参数,然后在服务器端进行拆分.

  • @larschanders我仍然得到了投票,但你为什么不接受这个答案呢?:) (3认同)