Datatable转换为Json 然后把Json数据放入 js 文件中

C#中把Datatable转换为Json的5个代码实例

        ///      
        /// Datatable转换为Json     
        ///     
        /// Datatable对象     
        /// Json字符串     
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        /// 
        /// 格式化字符型、日期型、布尔型
        /// 
        /// 
        /// 
        /// 
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }
        /// 
        /// 过滤特殊字符
        /// 
        /// 字符串
        /// json字符串
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }  


<2>

//从数据库里查询出省名
            var sql = "select top 35 locid,locname,parentid from location where loctype=1";
            var dt_pro = SQLHelper.Get_DataTable(sql, SQLHelper.GetCon(), new Dictionary());
            //将dt_pro这个DataTable转换成json
            var tt_pro = ToJson(dt_pro);

            //查询出城市的名称
            var vsql = "select locid,locname,parentid from location where parentid in (select top 35 locId from location where loctype=1) ";
            
            var dt_city = SQLHelper.Get_DataTable(vsql, SQLHelper.GetCon(), new Dictionary());
            //将dt_city这个DataTable转换成json
            var tt_city = ToJson(dt_city);

<3> 建立一个js 文件 在文件里  写两个变量 var cn_pro,和var cn_city 将 tt_pro的值赋值给 cn_pro ,将tt_city的值赋值 cn_city 就成了一个js 文件了

js内如入 var cn_pro = [{ "locid": 1, "locname": "北京", "parentid": 0 }, { "locid": 673, "locname": "上海", "parentid": 0 }];

var cn_city = [{ "locid": 2, "locname": "北京", "parentid": 1 }, { "locid": 674, "locname": "上海", "parentid": 673 }]


当然我这是简写的,里面的内如大多都去掉了。就保留了前面2条数据做示例


================================================================

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MemberCenter.Master"
     Inherits="System.Web.Mvc.ViewPage"%>
    <%@ Import Namespace="bigtree" %>

        
    <% using (Html.BeginForm()) {%>

    
    

个人资料

  • 手机:

    <%----%> <%: Html.TextBoxFor(x => x.Mobile, new { @class = "setterInput fl" ,@readonly=""})%>
    (请填写真实入住人姓名,每间房只填写以为即可)
  • 姓名:

    <%----%> <%: Html.TextBoxFor(x => x.Name, new { @class = "setterInput fl"})%>
  • 邮箱:

    <%-- --%> <%: Html.TextBoxFor(x => x.Email, new { @class = "setterInput fl" })%> <% var i = Model.EmailFlag; if (i == true) { %>
    已验证
    <% }%> <% else {%>
    未验证
    <% }%>
  • 昵称:

    <%----%> <%: Html.TextBoxFor(x=>x.UserName,new {@class="setterInput fl"}) %>
  • 性别:

  • <% var province = ViewData["province"] as System.Data.DataTable;%>
  • 常用出发城市:

    北京

    北京

<% } %>


你可能感兴趣的:(AJAX,JSON,JavaScript)