/// 页面加载时
///
///
///
protected void Page_Load(object sender, EventArgs e)
{
//判断是否异步请求
if (Request.QueryString["ajax"] == "1")
{
ProcessRequest();
}
}
///
/// 处理异步请求
/// private void ProcessRequest()
{
Response.ContentType = "text/html";
string json = Request.Form["json"];
//反序列化DataTable
DataTable newdtb = Json2Dtb(json);
//序列化DataTable为JSON
string back = Dtb2Json(newdtb);
Response.Write(back);
Response.End();
}
///
/// DataTable转Json
/// ///
///
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary
drow = new Dictionary();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
///
/// Json转DataTable
///
///
///
private DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize(json);
DataTable dtb = new DataTable();
if (dic.Count > 0)
{
foreach (Dictionary drow in dic)
{
if (dtb.Columns.Count == 0)
{
foreach (string key in drow.Keys)
{
dtb.Columns.Add(key, drow[key].GetType());
}
}
DataRow row = dtb.NewRow();
foreach (string key in drow.Keys)
{
row[key] = drow[key];
}
dtb.Rows.Add(row);
}
}
return dtb;
}