.net后台获取DataTable数据,转换成json数组后传递到前台,通过jquery去操作json数据

时间:2023-11-28 14:39:08

一,后台获取json数据
protected void Page_Load(object sender, EventArgs e){
  DataTable dt = DBhepler.GetDataTable("select top 100 * from Tstudent");
  jsn = DataTable2Json(dt);
}

public string jsn = "";

public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();

jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
 jsonBuilder.Append("{");
 for (int j = 0; j < dt.Columns.Count; j++)
 {
     jsonBuilder.Append("\"");
     jsonBuilder.Append(dt.Columns[j].ColumnName);
     jsonBuilder.Append("\":\"");
     jsonBuilder.Append(dt.Rows[i][j].ToString());
     jsonBuilder.Append("\",");
  }
   jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
   jsonBuilder.Append("},");
 }
 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
 jsonBuilder.Append("]");
 return jsonBuilder.ToString();

}

二,前台取值
var json = '<%=jsn %>';
var objJson = jQuery.parseJSON(json);
var str = "";
for (var i = 0; i < objJson.length; i++) {
str += objJson[i].id + ", "
}