Datatable轉換為Json 然後把Json資料放入 js 檔案中

來源:互聯網
上載者:User

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"}) %>
  • 性別:

    <%----%> <%:Html.RadioButtonFor(x=>x.Sex,"男", new{@name="sex"})%> 男 <%----%> <%: Html.RadioButtonFor(x=>x.Sex,"女", new{@name="sex"})%> 女
  • <% var province = ViewData["province"] as System.Data.DataTable;%>
  • 常用出發城市:

    北京

    北京

<% } %> <script type="text/javascript"> $(function () { $(".navList > :contains('設定檔')").addClass("cur"); // set province var proList = ""; $.each(cn_pro, function (i, kv) { proList += "
  • " + kv.locname + "
  • "; }); $("#proList").html(proList); $("#proList li").bind("click", function () { var li = $(this); var cityList = ""; $.each(cn_city, function (i, kv) { if (kv.parentid == li.attr("data-id")) { cityList += "
  • " + kv.locname + "
  • "; } }); $("#cityList").html(cityList); $("#displyPro").text(li.text()); $("#displyCity").text($("#cityList").children().first().text()); $("#selectCityId").val($("#cityList").children().first().attr("data-id")); $("#selectCityName").val($("#cityList").children().first().text()); $("#cityList li").bind("click", function () { $("#displyCity").text($(this).text()); $("#selectCityId").val($(this).attr("data-id")); $("#selectCityName").val($(this).text()); }); }); }) </script> <script type="text/javascript" src="../../Scripts/Location.js"></script>


    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.