2

How to pass an array to webmethod using the following code:

$.ajax({
    type: "POST",
    url: "somepage.aspx/somemethod",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
user384080
  • 4,576
  • 15
  • 64
  • 96
  • Please see this answer for a working example: http://stackoverflow.com/questions/7971393/passing-array-of-strings-to-webmethod-with-variable-number-of-arguments-using-jq/7972325#7972325 – weir Nov 02 '11 at 00:57

2 Answers2

2

just arrays...

$.ajax({
    type: "POST",
    url: "somepage.aspx/somemethod",
    data: "a[1]=1&a[2]=2&a[3]=3",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

you might do also on objects...

var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
};
$.ajax({
    type: "POST",
    url: "somepage.aspx/somemethod",
    data: decodeURIComponent($.param(myObject)), // a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

you can look at more options of $.ajax(), these includes data

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • Good answer Reigel. OP, please see the `data` option: http://api.jquery.com/jQuery.ajax/ – karim79 Jul 07 '10 at 01:41
  • the webmethod has the following signature but it is not getting called: [WebMethod] public static string somemethod(string[] arg) { } – user384080 Jul 07 '10 at 02:38
  • what scripting language are you using? ASP.NET? – Reigel Gallarde Jul 07 '10 at 02:43
  • I have the js file which contains: var array = new Array(); $.ajax({ type: "POST", url: "somepage.aspx/somemethod", data: array contentType: "application/json; charset=utf-8", dataType: "json" }); and the method in the aspx.cs: [WebMethod] public static string somemethod(string[] arg) { } – user384080 Jul 07 '10 at 09:20
  • Reigel - can u please show me the signature of your "somemethod" method would be? – user384080 Jul 07 '10 at 09:41
  • I'm curious. are you in PHP? ASP.NET? and what are you expecting for `somemethod`? – Reigel Gallarde Jul 07 '10 at 09:44
  • it is asp.net (Please see my previous reply - 33 minutes ago) – user384080 Jul 07 '10 at 09:55
  • How do you get the query string from ajax if the "somemethod" method is signed by static attribute? but on the other side if the "somemethod" is not signed by static attribute, it won't get called.. so confusing... :( – user384080 Jul 07 '10 at 10:30
-1

I use something similiar to the following method

var your_array = new array();
your_array[0] = 1;
your_array[1] = 2;

var data = { numbers: [] };

data.numbers = your_array;

$.ajax({
    type: "POST",
    url: "somepage.aspx/somemethod",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data = json_data
});
Germán Rodríguez
  • 4,284
  • 1
  • 19
  • 19