Pass array to code behind from jquery ajax

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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?

回答1:

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)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!