Sending a javascript array to code behind(c#) using ajax

asp.net, c#, javascript, jquery, webforms

Solution

I have written a in-depth example for this using ASP.NET MVC, but it can easily be adapted for WebForms.

Send data with jquery to an MVC controller

The HTML and jQuery will look almost exactly the same, with the exception of where you call the WebMethod.

If the page you are using is called `Default.aspx`, and the method is called `Done`, then your URL for the WebMethod will be `Default.aspx/Done`.

<script>
       // Grab the information 
       var values = {"1,","2","3"};
       var theIds = JSON.stringify(values);

       // Make the ajax call
       $.ajax({
         type: "POST",
         url: "Default.aspx/Done", // the method we are calling
         contentType: "application/json; charset=utf-8",
         data: {ids: theIds },
         dataType: "json",
         success: function (result) {
             alert('Yay! It worked!');               
         },
         error: function (result) {
             alert('Oh no :(');
         }
     });
  </script>

Your `WebMethod` will still be the same.

[WebMethod]
public static void done(string[] ids)
{
   String[] a = ids;
   // Do whatever processing you want
   // However, you cannot access server controls
   // in a static web method.
}

Problem

I'm a bit new to C# and javascript so while my question is specific I am open to any alternatives. I have an array of values (that I have created in a javascript function) that I want to send to my code-behind file to be used in a method. From what I've researched using ajax and stringifying the array with JSON seems like the best method. My questions are Can I pass the array using this method? How do I capture the information on the server side(in my code-behind?) Javascript passing the values ``` var jsonvalues = JSON.stringify(values); var callback = window.location.href $.ajax({ url: callback type: "POST", contentType: 'application/json', data: jsonvalues }); ``` I've seen many solutions using [WebMethod] or some kind of WebService to capture the data, can I use this to do work in my code-behind file without having to return data? Here is what I'm using on my code-behind file ``` [WebMethod] public static void done(string[] ids) { String[] a = ids; } ```

Original source

Related problems