Using ajax to submit an array to an asp.net page

The following submits an array of strings to an asp.net razor page for handling. It is not straightforward how to submit an array for processing. You have to first stringify it before sending with ajax. Once it is received, you have to then deserialize it into a List..

Suppose you have an array of strings: myarray= [‘blue’,’green’, ‘red’]; You want to ajax it to a razor page or any other asp.net handler. The ajax stringifies the data and then submits.

myarray= ['blue', 'green', 'red'];
 $.ajax({
        url: "/?handler=ProcessArray",
        timeout: 6000, //6 second timeout
        method: "Get",
        data: { "myInput": JSON.stringify(myarray) },
        success: function (result, status) {
           
            return result;
        },
        error: function (request, status, error) {
            alert(request.responseText);
        }

});

Here is the handler.

   public IActionResult OnGetProcessArray( string myInput)
        {

            var myarraylist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<String>>(myInput);
             foreach (String item in myarraylist)
                    {
                             ...
                     }

            ....
           return Content(result);
       }

The handler receives the data as a string . It then deserializes it into a list of Strings using Newtonsoft.JsonConvert. Once you have a List of type String, myarraylist, you can process the list with a foreach loop.

Leave a Reply

Your email address will not be published. Required fields are marked *