Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array to code behind from jquery ajax

I have to pass two dimensional array to the page method written at code behind of the web page in asp.net I have a variable objList as a two dimensional array. I used following code for achieving this with no success and page method is not called.

JAVASCRIPT

function BindTable(objList) {

    $.ajax(
    {
           url: "CompCommonQues.aspx/SaveData",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           type: "POST",
           data: { data: objList },
           success: function (data) {
           //Success code here
    },
    error: function () { }
    });
  }

CODE BEHIND .CS File

 [WebMethod]
public static string SaveData(string[,] data)
{
    string[,] mystring = data;
    return "saved";
}

There is method like JSON.stringify(objList) to pass the json array to code behind but couldn't implement this. A simple call wihtout array working for me like

data: "{ 'data':'this is string' }",

and in code behind

[WebMethod]
public static string SaveData(string data)
{
    string mystring = data;
    return "saved";
}

There is problem in passing data. Can you assist me how to pass it for arrays?

like image 871
Rajaram Shelar Avatar asked Mar 29 '13 07:03

Rajaram Shelar


1 Answers

Try the correct JSON notation in JavaScript

var objList = new Array();
objList.push(new Array("a","b"));
objList.push(new Array("a", "b"));
objList.push(new Array("a", "b"));

   $.ajax({
       type: "POST",
       url: "copyproduct.aspx/SaveDate",
       data: "{'data':'" + JSON.stringify(objList) + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
            alert(msg.d);
       }
   });

In code behind, you can deserialize with JavaScriptSerializer (System.Web.Script.Serialization)

[WebMethod()]
public static string SaveDate(string data)
{
    JavaScriptSerializer json = new JavaScriptSerializer();
    List<string[]> mystring = json.Deserialize<List<string[]>>(data);
    return "saved";
}

I had to deserialize to a generic list of a string array because you can't deserialize to a string (check: http://forums.asp.net/t/1713640.aspx/1)

like image 72
CyclingFreak Avatar answered Jan 09 '23 12:01

CyclingFreak