Pass array to code from jquery ajax

I need to pass a two-dimensional array to a page method written on the code end of a web page in asp.net. I have an objList variable as a two-dimensional array. I used the following code to achieve this without success, and the 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 a method like JSON.stringify (objList) to pass the json array to the code, but could not implement this. A simple call with an array that works for me as

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

and in code

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

Along the way, data passes. Can you help me how to pass it for arrays?

+7
source share
1 answer

Try the correct JavaScript JSON Notation

 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 the code behind, you can deserialize using the 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 a generic list of string array because you cannot deserialize a string (check: http://forums.asp.net/t/1713640.aspx/1 )

+6
source

All Articles