Long title, but this is a problem that has haunted me for a while now. I have an Asp.Net WebMethod that takes a List/IEnumerable/Array of stuff as a parameter, how do I send that stuff to that method using the JQuery Ajax method.
Now, without having to reinvent the wheel, do check out David Ward’s articles on JQuery and Asp.Net WebMethods for a primer on how this is done.
But one item not mentioned is how to update methods that take lists.
If you want to know why this is hard, take a look at this sample. If you have a web method that looks like this:
You are going to call it with code like this:
If you are still wondering where this issue is, look at line 4 of the second sample there.
But there is a way.
(Side note: if anyone has contact info on Mr. Crockford, I’d love to do a podcast with him as well)
JSON2.js gives you a method called JSON.stringify. Which takes an object and returns a string. All this in a class that can be minified to less than 2.5K.
Now, lets put this to work.
I’m going to create a new WebMethod:
Here is my JQuery code:
And it works! If you are worried that I’m sending too simple an object here (a simple list of strings in this example), I have tested this with much more complex object types as well, and it still works wonderfully.