Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters in a jQuery ajax call to an ASP.NET webmethod

I know there are more threads about this but they dont help me and I'm going insane here!

I wanna pass some parameters in to a web method using jQuery Ajax.

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) {

        }
    });

In the ajax call, if I put data to paramList I get the error: "Invalid web service call, missing value for parameter: \u0027a\u0027."

If I put data to jsonParams I get the error:

"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027"

If I write out paramList, it's in a correct JSON format like {"id":"140", "id":"138"}

If I write out jsonParams, it's in an incorrect format like "{\"id\":\"140\",\"id\":\"138\"}"

The web method: (it doesn't do that much yet..)

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

What am I doing wrong? Can't seem to get this JSON thing right.

UPDATE:

After some help from the first answer I now send {"id":["138","140"]} in the AJAX request.

The web method now takes a string called id as the parameter instead.

[System.Web.Services.WebMethod]
public static string UpdateSequenceNumber(string id)
{
     return id;
}

Now I get the new error:

"Type \u0027System.Array\u0027 is not supported for deserialization of an array."

like image 445
larschanders Avatar asked Nov 22 '10 09:11

larschanders


People also ask

How do you pass parameters to WebMethod?

Answers. if that particular webservice is in your application iself. then you can directly call it with methodname(param)... if that service is outside your app, then make a httpwebrequest and then pass the parameter as per service stats, i mean eeither in querystring or in Request stream...


1 Answers

Your json parameter names must be same with the c# paramter names.

{"a":"140", "b":"138"}

If you are sending unknown number of parameters to server, you may concat at client-side into one parameter and then split at server-side.

like image 77
Ahmet Kakıcı Avatar answered Oct 15 '22 04:10

Ahmet Kakıcı