I have been tortured by jquery recently and made a demo of jquery parsing json. This demo wants to instantiate a dataSet or dataTable data set from the asp.net background, convert the dataSet into json and return it to the client. The client Use the jquery getJson method to parse it and display it on the page.
First, let’s briefly introduce the getJson method
Jquery.getJson(url,[data],[callback])
url: Send request address.
data: Key/value parameters to be sent.
callback: callback function when loading is successful.
The following is the actual getJson method
First create an auxiliary class to convert the dataset data set into a json string
public static string DataTableToJson(string jsonName, DataTable dt)
{
StringBuilder Json = new StringBuilder();
Json.Append("{"" jsonName "":[ ");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i )
{
Json .Append("{");
dt.Columns[j]. ColumnName.ToString() "":"" dt.Rows[i][j].ToString() """);
> Json.Append(","); son.Append("}");
Json.Append(","); Json.Append("]}");
return Json.ToString();
}
This method is an auxiliary class method on msdn.
The second step is to manually configure and create a demonstration Dataset, but in the project, the data is usually obtained from the database or service
Copy code
The code is as follows:
public static DataSet BindData()
{
DataTable dtData = new DataTable();
dtData.Columns.Add("id");
dtData.Columns.Add("name");
dtData.Columns.Add("sex");
DataRow drData;
drData = dtData.NewRow();
drData[0] = 16;
drData[1] = "zhaoliu";
drData[2] = "man";
dtData.Rows.Add(drData);
drData = dtData.NewRow();
drData[0] = 19;
drData[1] = "zhangsan";
drData[2] = "women";
dtData.Rows.Add(drData);
DataSet ds = new DataSet();
ds.Tables.Add(dtData);
return ds;
}
第三步 创建aspx页面
前台页面:两个button,一个单击开始解析json数据,另外一个查看json字符串
后台页面:
protected void Page_Load(object sender, EventArgs e)
{
JsonAjax();
}
private void JsonAjax() {
string action = Request["Action"];
if (!string.IsNullOrEmpty(action) && action == "action") // 判断が前台の点击イベントを通過したかどうか
{
string str = DataTableConvertJson.DataTableToJson("json", Data.BindData().Tables[0]);
応答.書き込み(文字列) ;
Response.End();
}
}
最終给大家展示一次生成的json格式:
フォームの先頭
{"json":[{"id":"16","name":"zhaoliu","sex":"man"},{"id":"19","name":"zhangsan ","性別":"女性"}]}
フォームの下側