JavaScript Arrays via JQuery Ajax to an ASMX WebMethod
Posted by mariuszrokita on February 8, 2012
This is a problem that has haunted me today. So… I have a WebMethod in an ASMX WebService. That method takes 3 parameters: string, integer and a List/IEnumerable/Array of strings. There is also a JavaScript code, that should execute the WebMethod using JQuery AJAX method. And this way the problem has arisen: how to send the JavaScript array as a List/IEnumerable/Array?
To understand and solve the problem it was really good to read following articles:
- JavaScript Arrays via JQuery Ajax to an Asp.Net WebMethod
- Using jQuery to Consume ASP.NET JSON Web Service
- A breaking change between versions of ASP.NET AJAX
So now it’s time for a solution…
The WebMethod that should be called:
And the snippet from corresponding JavaScript file:
As you can see, I’ve instantiated the ‘dataToPass’ object that contains all the data that will be passed to WebMethod. Then I’ve created the JSON string by serializing the ‘dataToPass’ object. It was done by using the json2.js plugin. And finally, such text containing JSON content could be passed as a parameter to the JQuery Ajax method.