Datatable转换为Json 然后,Json数据导入 js 档

时间:2022-01-24 03:46:51

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>

版权声明:本文博主原创文章,博客,未经同意不得转载。