C# DataTable 转为 javaScript Array并且在页面中访问数组
DataTable 转换为javascript数据并且在页面中读取,在Codes Behind写入:
using System.Data;
using System.Collections;
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtInfo = new DataTable();
dtInfo.Columns.Add("Name");
dtInfo.Columns.Add("Marks");
dtInfo.Columns.Add("Age");
DataRow dr = dtInfo.NewRow();
dr["Name"] = "Amit";
dr["Marks"] = "67";
dr["Age"] = "23";
dtInfo.Rows.Add(dr);
string str = Dtb2Json(dtInfo);//JSONHelper.FromDataTable(dtInfo);
System.Text.StringBuilder javaScript = new System.Text.StringBuilder();
javaScript.Append("<script type=\"text/javascript\">");
javaScript.Append("var students =");
javaScript.Append(str + ";");
javaScript.Append("</script>");
ClientScript.RegisterClientScriptBlock(GetType(), "ArrayScript", javaScript.ToString(), false);
}
/// <summary>
/// DataTable转Json
/// </summary>
/// <param name="dtb"></param>
/// <returns></returns>
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
在前台页面中写入:
<script type="text/javascript">
alert(students[0].Name);
</script>
如果有Master Page,请添加它到<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">中。
posted on 2012-09-28 14:35 elvis blogs 阅读(652) 评论(0) 编辑 收藏 举报