elvis blogs

日子过得很有意义,我们产出了很多,也消费了很多!在这个过程中,我们汲取了养份和能量又即将发挥在不久的将来!我们努力着,拼博着并快乐着!

导航

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编辑  收藏  举报