Adonis Alex Adonis Alex - 5 months ago 6
jQuery Question

How to pass array as an argument to server method via jQuery+Ajax

Well I am developing a web application in Asp.Net and in the code behind I am using C#. I've successfully written code to pass a class object to code behind method but I am wondering how to pass an array as an argument via ajax and jQuery.

I've tried something but it didn't work. Here is my code what I am trying to run

function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: '{args: ' + argu + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}


And this is my code behind method which is written in C#.

[WebMethod]
[ScriptMethod]
public static bool Foo(int[] args)
{
return true;
}


Application built successfully. I have put break points but my code behind method doesn't fire. I am wondering Where is the problem? What else I am missing here?

Answer

Well all code seems good enough to make a call but I think the problem is in passing the data in your code.

It should be like.

data: '{args: ' + JSON.Stringify(argu) + '}'

And finally your code should be like

function Test(){
var argu = [1, 2];
$.ajax({
        type: 'POST',
        url: 'MyPage.aspx/Foo',
        data: '{args: ' + JSON.Stringify(argu) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
           // Success
        },
        error: function (response) {
           // Failed
        }
      });
}

Hope that helps.

Comments