Popokoko
Popokoko

Reputation: 6543

Jquery, Ajax, C#: pass array data to server side

I'm trying to do something but with no success. 1. I want to do an ajax call by jquery and to pass an array (i assumed it should be on the data property). 2. Then, i want to retrieve this array on the server side but im pretty lost how.

Can anyone please explain how can this be easily done? I thought about using context.Request.Params but im guessing this is not the right way..

var array = [];
...

 $.ajax({
      cache: false,
      method: 'json',
      url: 'handler/myhandler.ashx',
      data: array

Upvotes: 1

Views: 5436

Answers (2)

Jack
Jack

Reputation: 2660

using JSON.stringify() like this:

 $.ajax({
      cache: false,
      method: 'json',
      url: 'handler/myhandler.ashx',
      data: JSON.stringify(array),
      type: "POST"

After data gets send to the server side, all you need to do now is to deserialize the object, this is how you do it

//might be something else other than Forms["json"], use debug mode to figure out the param
    string json = HttpContext.Current.Request.Forms["json"];
    JavaScriptSerializer  serializer= new JavaScriptSerializer();
    var urObj = serializer.Deserialize<Type>(json);

Upvotes: 0

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

EDIT: I just realized you need to "post" your data. You should add "type: 'POST'" to your ajax call :)

 $.ajax({
      type: 'POST',
      cache: false,
      method: 'json',
      url: 'handler/myhandler.ashx',
      data: array

You are correct, your array should be inserted into the "data" property of the ajax call.

You can access the data on the server side through the HttpContext in your handler. There is an attribute called request.

For converting the object into an object, here's a deserializsation example. Where it is deserialized into a dictionary.

public void ProcessRequest(HttpContext context)
{
    var data = context.Request;
    var sr = new StreamReader(data.InputStream);
    var stream = sr.ReadToEnd();

    var javaScriptSerializer = new JavaScriptSerializer();

    var arrayOfStrings = javaScriptSerializer.Deserialize<string[]>(stream);

Upvotes: 2

Related Questions