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

來源:互聯網
上載者:User

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

C#中把Datatable轉換為Json的5個代碼執行個體

        /// <summary>             /// Datatable轉換為Json             /// </summary>            /// <param name="table">Datatable對象</param>             /// <returns>Json字串</returns>             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();        }        /// <summary>        /// 格式化字元型、日期型、布爾型        /// </summary>        /// <param name="str"></param>        /// <param name="type"></param>        /// <returns></returns>        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;        }        /// <summary>        /// 過濾特殊字元        /// </summary>        /// <param name="s">字串</param>        /// <returns>json字串</returns>        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<string, DBParam>());            //將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<string, DBParam>());            //將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<bigtree.Model.MemberDetail>"%>    <%@ Import Namespace="bigtree" %><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">            <% using (Html.BeginForm()) {%>        <div class="rightCon">        <div class="nowTil">            <h3>                設定檔</h3>        </div>        <ul class="memForm">            <li>                <p class="setterTil">                    手機:</p>                <div class="setterBd">                    <%--<input type="text" class="setterInput fl" value="" readonly="">--%>                    <%: Html.TextBoxFor(x => x.Mobile, new { @class = "setterInput fl" ,@readonly=""})%>                                       <div class="setterExplain">                        (請填寫真實入住人姓名,每間房只填寫以為即可)</div>                </div>            </li>            <li>                <p class="setterTil">                    姓名:</p>                <div class="setterBd">                    <%--<input type="text" class="setterInput fl" value="張小凡" readonly="">--%>                    <%: Html.TextBoxFor(x => x.Name, new { @class = "setterInput fl"})%>                </div>            </li>            <li>                <p class="setterTil">                    郵箱:</p>                <div class="setterBd">                   <%-- <input type="text" class="setterInput fl">--%>                    <%: Html.TextBoxFor(x => x.Email, new { @class = "setterInput fl" })%>                                            <% var i = Model.EmailFlag;                           if (i == true)                           { %>                                                        <div class="setterExplain">已驗證</div>                                                    <% }%>                            <% else {%>                              <div class="setterExplain">未驗證</div>                           <% }%>                                                       </div>            </li>            <li>                <p class="setterTil">                    暱稱:</p>                <div class="setterBd">                    <%--<input type="text" class="setterInput fl">--%>                    <%: Html.TextBoxFor(x=>x.UserName,new {@class="setterInput fl"}) %>                </div>            </li>            <li>                <p class="setterTil">                    性別:</p>                <div class="setterBd">                    <label class="sex">                        <%--<input type="radio" name="sex">--%>                        <%:Html.RadioButtonFor(x=>x.Sex,"男", new{@name="sex"})%>                        男</label>                    <label class="sex">                        <%--<input type="radio" name="sex">--%>                        <%: Html.RadioButtonFor(x=>x.Sex,"女", new{@name="sex"})%>                        女</label>                </div>            </li>            <% var province = ViewData["province"] as System.Data.DataTable;%>            <li>                <p class="setterTil">                    常用出發城市:</p>                <div class="setterBd">                    <div class="selectBox sp1 fl">                        <p id="displyPro" class="getNum sp3">                            北京</p>                        <div class="xjt">                        </div>                        <ul id="proList" class="selectSlideBox none sp3" style="">                        </ul>                    </div>                    <div class="setterExplain sp">                        省</div>                    <div class="selectBox sp1 fl">                        <p id="displyCity" class="getNum sp3">                            北京</p>                        <div class="xjt">                        </div>                        <ul id="cityList" class="selectSlideBox none sp3" style="">                        </ul>                    </div>                    <div class="setterExplain">                        市</div>                </div>            </li>        </ul>        <input type="hidden" id="selectCityId" value="1" />        <input type="hidden" id="selectCityName" value="北京" />        <input type="submit" value="儲存" class="saveBtn">    </div>    <% } %></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">    <script type="text/javascript">        $(function () {            $(".navList > :contains('設定檔')").addClass("cur");            // set province            var proList = "";            $.each(cn_pro, function (i, kv) {                proList += "<li data-id='" + kv.locid + "'>" + kv.locname + "</li>";            });                      $("#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 += "<li data-id='" + kv.locid + "'>" + kv.locname + "</li>";                    }                });                $("#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></asp:Content>



C#怎將datatable資料轉換成json

/// <summary>
/// 將datatable轉換為json
/// </summary>
/// <param name="dtb">Dt</param>
/// <returns>JSON字串</returns>
public static string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
System.Collections.ArrayList dic = new System.Collections.ArrayList();
foreach (DataRow dr in dtb.Rows)
{
System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
foreach (DataColumn dc in dtb.Columns)
{
drow.Add(dc.ColumnName, dr[dc.ColumnName]);
}
dic.Add(drow);

}
//序列化
return jss.Serialize(dic);
}
 
jstree做動態樹,json格式傳輸,預存程序獲得datatable之類,不知道怎把datatable轉換為需要的json資料格式

datatable就是一個表格而已,你for遍曆一下就可以取出裡面的任意資料了啊,然後拼接成json字串不就行了。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.