首先給出數據庫表,很簡單只是一張後臺數據字典表javascript
分頁存儲過程css
USE [ECLProduct] GO /****** Object: StoredProcedure [dbo].[UP_GetRecordByPage] Script Date: 07/06/2013 12:04:55 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= ALTER PROCEDURE [dbo].[UP_GetRecordByPage] -- Add the parameters for the stored procedure here @tblName varchar(255), ------表名 @fldName varchar(255), -- 排序的字段名 @PageSize int , @PageIndex int , @IsReCount bit, -- 返回記錄總數, 非 0 值則返回 @OrderType bit, -- 設置排序類型, 非 0 值則降序 @strWhere varchar(1000), -- 查詢條件 @pageCount int output --計算 總共多少頁 AS BEGIN declare @count int --總共多少條 select @count =COUNT(*) from [ECLProduct].[dbo].[AD_DATA_DICTIONARY] set @pageCount = CEILING( @count*1.0/@pageSize) if(@strWhere='') begin select * from (select *,ROW_NUMBER() over(order by DictionaryCode desc) as num from [ECLProduct].[dbo].[AD_DATA_DICTIONARY]) as t where num between @pageSize*(@pageIndex-1) + 1 and @pageSize*@pageIndex end else begin select * from (select *,ROW_NUMBER() over(order by DictionaryCode desc) as num from [ECLProduct].[dbo].[AD_DATA_DICTIONARY]) as t where (num between @pageSize*(@pageIndex-1) + 1 and @pageSize*@pageIndex) and DictionaryName=@strWhere end END
列表頁面html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <link href="../../Styles/PageControlStyle.css" rel="stylesheet" type="text/css" /> <link href="../../Styles/GridStyle.css" rel="stylesheet" type="text/css" /> <link href="../../Scripts/layer/skin/layer.css" rel="stylesheet" type="text/css" /> <link href="../../Styles/cerulean.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="../../Scripts/layer/layer.min.js" type="text/javascript"></script> <style type="text/css"> .divSearchResultPages { cursor:pointer; } .pre-page { overflow:hidden; padding:2px 6px 3px 15px; background:url("../../Images/page_nav.gif") 7px -15px no-repeat #ffffff; border: 1px solid #ccc; } .next-page { overflow:hidden; padding:2px 12px 3px 6px; background:url("../../Images/page_nav.gif") 44px 5px no-repeat #ffffff; border: 1px solid #ccc; } .begining {padding:2px 6px 3px 15px; border: 1px solid #ccc; } .ending {padding:2px 12px 3px 6px; border: 1px solid #ccc; } </style> <script type="text/javascript"> var searchsName = ""; //查詢所需變量 var CurrentPage = 1; var countPage = 0; var pageSize = 10; $(document).ready(function () { loadList(CurrentPage, pageSize, ''); }); function loadList(pageindex, pagesize, searchsName) { jQuery.ajax({ type: "GET", url: "AD_DATA_DICTIONARY.ashx", cache: false, data: { type: "GetPage", Pageindex: pageindex, PageSize: pagesize, searchsName: searchsName }, dataType: "json", success: function (data) { if (data) { if (data == 'unlogin') { parent.CheckSession(0); } else { data.toString(); countPage = data.Key; CurrentPage = pageindex; jQuery("#spanCurrentPage").html(CurrentPage); jQuery("#spanPageCount").html(countPage); if (jQuery("#tb").length > 0) { jQuery("#tb").remove(); } var $tb = $("<table id='tb'class='table table-striped table-bordered bootstrap-datatable datatable dataTable'></table>"); $("#tbdiv").append($tb); var $th = $("<tr style='background-color: #e8e8e8'><th style='width: 160px;'>字典名稱</th><th style='width: 160px;'>來源</th><th style='width: 160px;'>順序號</th><th style='width: 160px;'>描述說明</th><th style='width: 160px;'>字典值</th><th style='width: 160px;'>類型代碼</th><th style='width: 160px;'>控制等級</th><th style='width: 160px;'>是否禁用</th><th style='width: 311px;'>編輯</th></tr>"); $("#tb").append($th); var obj = jQuery.parseJSON(data.Value); for (var i = 0; i < obj.length; i++) { var $tr = jQuery("<tr ></tr>"); $tb.append($tr); // //字典代碼 // var $td = jQuery("<td >" + obj[i].DictionaryCode + "</td>"); // $tr.append($td); //字典名稱 var $td = jQuery("<td >" + obj[i].DictionaryName + "</td>"); $tr.append($td); //來源 var $td = jQuery("<td >" + obj[i].DictionaryFrom + "</td>"); $tr.append($td); //順序號 var $td = jQuery("<td >" + obj[i].SequenceNumber + "</td>"); $tr.append($td); //描述說明 var $td = jQuery("<td >" + obj[i].Description + "</td>"); $tr.append($td); //字典值 var $td = jQuery("<td >" + obj[i].DictionaryValue + "</td>"); $tr.append($td); //類型代碼 var $td = jQuery("<td >" + obj[i].TypeCode + "</td>"); $tr.append($td); //控制等級 var $td = jQuery("<td >" + obj[i].Level + "</td>"); $tr.append($td); //是否禁用 var status = obj[i].IsDisabled == true ? "是" : "否"; var $td = jQuery("<td >" + status + "</td>"); $tr.append($td); // //建立人 // var $td = jQuery("<td >" + obj[i].Creator + "</td>"); // $tr.append($td); // //建立時間 // var $td = jQuery("<td >" + obj[i].CreateDate + "</td>"); // $tr.append($td); var TempStr = "<a class='btn btn-info' href='javascript:viod(0)' onclick=\"showAdd('AddDateDictionary.html?DictionaryCode=" + obj[i].DictionaryCode + "&&type=modify','編輯字典')\"><i class='icon-edit icon-white'></i>Edit</a>"; TempStr += "<a class='btn btn-danger' href='javascript:void(0)' onclick='deleteDictionary(\"" + obj[i].DictionaryCode + "\")' ><i class='icon-trash icon-white'></i>Delete</a> " $td = jQuery("<td >" + TempStr + "</td>"); $tr.append($td); } } } }, error: function (errorMessage) { alert(errorMessage.responseText); } }); } // 查詢按鈕、翻頁按鈕 響應事件 function searchPlus(type) { switch (type) { case -2: //首頁 CurrentPage = 1; break; case -1: //上一頁 CurrentPage = CurrentPage <= 1 ? 1 : CurrentPage - 1; break; case 0: searchsName = jQuery("#DictionaryName").val() == jQuery("#DictionaryName").attr("rel") ? "" : jQuery("#DictionaryName").val(); CurrentPage = 1; break; case 1: //下一頁 CurrentPage = CurrentPage >= countPage ? countPage : CurrentPage + 1; break; case 2: //尾頁 CurrentPage = countPage; break; } loadList(CurrentPage, pageSize, searchsName); } //刪除數據字典 function deleteDictionary(DId) { // $.layer({ // shade: false, // area: ['auto', 'auto'], // dialog: { // msg: '您是如何看待前端開發?', // btns: 2, // type: 4, // btn: ['重要', '奇葩'], // yes: function () { // layer.msg('您選擇了重要。', 2, 1); // jQuery.ajax({ // type: "GET", // url: "AD_DATA_DICTIONARY.ashx", // data: { type: "delete", data: DId }, // dataType: "text", // cache: false, // success: function (data) { // if (data) { // if (data == 'unlogin') { // parent.CheckSession(0); // } else { // loadList(CurrentPage, pageSize, searchsName); // alert("刪除成功!"); // } // } // }, // error: function (errorMessage) { // alert(errorMessage.responseText); // loadList(CurrentPage, pageSize, searchsName); // } // }); // }, // no: function () { // layer.msg('奇葩!!!', 2, 4); // } // } // }); // if (layer.confirm("確認刪除活動!")) { // // } layer.confirm('肯定刪除?', function () { jQuery.ajax({ type: "GET", url: "AD_DATA_DICTIONARY.ashx", data: { type: "delete", data: DId }, dataType: "text", cache: false, success: function (data) { if (data) { if (data == 'unlogin') { parent.CheckSession(0); } else { loadList(CurrentPage, pageSize, searchsName); // alert("刪除成功!"); layer.alert('刪除成功!') } } }, error: function (errorMessage) { layer.alert(errorMessage.responseText); loadList(CurrentPage, pageSize, searchsName); } }); }); } function searcherTarget(target) { loadList(CurrentPage, pageSize, $("#DictionaryName").val()); } function showAdd(src, title) { $.layer({ type: 2, title: title, iframe: { src: src }, area: ['450px', '400px'], offset: ['150px', ''], close: function (index) { // layer.msg('您得到了子窗口標記:' + layer.getChildFrame('#name').val(), 3, 1); layer.close(index); }, end: function () { loadList(CurrentPage, pageSize, ''); }//層關閉後刷新主頁面 }); } </script> </head> <body> <form id="form1" runat="server"> <div style="margin-top:20px;"> <a href="javascript:void(0)" class="btn btn-primary" style="width: 80px;" onclick="showAdd('AddDateDictionary.html?type=Add&&DictionaryCode=','新增字典')">新增字典</a> <input type="text" id="DictionaryName" /><input class="btn btn-primary" type="button" value="查詢" style="width: 80px;" id="searcher" onclick="searcherTarget(this)" /> </div> <div id="tbdiv"> </div> <div class="divSearchResultPages" style="margin-bottom:1px"> <span class="pre-page" onclick="searchPlus(-1)" style=" color:blue; ">上一頁</span> <span onclick="searchPlus(1)" class="next-page" style=" color:blue; ">下一頁</span> <span onclick="searchPlus(-2)" class="begining" style=" color:blue; ">首頁</span> <span onclick="searchPlus(2)" class="ending" style=" color:blue; ">尾頁</span> 共<span id="spanPageCount"></span>頁 第<span id="spanCurrentPage"></span>頁<br /> <br /> </div> </form> </body> </html>
增長和編輯頁面前端
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="../../Styles/cerulean.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery.form.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="../../Scripts/messages_cn.js.js" type="text/javascript"></script> <script src="../../Scripts/layer/layer.min.js" type="text/javascript"></script> <style type="text/css"> body { text-align: center; } .center { margin-top:10px; margin-right: auto; margin-left: auto; height: 200px; width: 400px; vertical-align: middle; line-height: 200px; } .error { color: Red; } ul, ol { list-style: none; } .panel-title { font-size: 12px; font-weight: bold; color: #0E2D5F; height: 16px; line-height: 16px; } .fitem { margin-bottom: 5px; } .fitem label { display: inline-block; width: 80px; } .btn { display: inline-block; vertical-align: baseline; width: auto; height: 16px; line-height: 16px; font-size: 12px; padding: 0; margin: 0; } </style> <script type="text/javascript"> var DictionaryCode = getQueryString('DictionaryCode'); var type = getQueryString('type'); $(document).ready(function () { if (DictionaryCode != null && DictionaryCode.length > 0 && type == "modify") { loadData(getQueryString('DictionaryCode')); $("#addform").validate(); } else { $("#addform").validate() } // bind 'myForm' and provide a simple callback function $('#addform').ajaxForm(function (data) { layer.alert(data); var index = parent.layer.getFrameIndex(); parent.layer.msg(data, 2, 1); parent.layer.close(index); //location.href = "AD_DATA_DICTIONARY.html"; }); $("#addform").attr("action", "AD_DATA_DICTIONARY.ashx?type=" + type + "&&dictionaryCode=" + DictionaryCode); }); /* 獲取URL參數 用法 getQueryString("參數名") */ function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } //編輯狀態初始化數據 function loadData(DictionaryCode) { jQuery.ajax({ type: "GET", url: "AD_DATA_DICTIONARY.ashx", data: { type: "getEditData", data: DictionaryCode }, dataType: "json", cache: false, async:false, success: function (data) { // var data = $.parseJSON(data); if (data) { if (data == 'unlogin') { parent.CheckSession(0); } else { $("#DictionaryCode").val(data[0].DictionaryCode); $("#DictionaryName").val(data[0].DictionaryName); $("#DictionaryFrom").val(data[0].DictionaryFrom); $("#SequenceNumber").val(data[0].SequenceNumber); $("#Description").val(data[0].Description); $("#DictionaryValue").val(data[0].DictionaryValue); $("#TypeCode").val(data[0].TypeCode); $("#Level").val(data[0].Level); $("#IsDisabled").attr('checked', data[0].IsDisabled == 0 ? false : true); } } } }); } </script> </head> <body> <form id="addform" action="AD_DATA_DICTIONARY.ashx?type=" method="post"> <div class="center"> <div class="panel-title"> <!--<div class="fitem"> 字典代碼: <input id="DictionaryCode" name="DictionaryCode" type="text" /> </div>--> <div class="fitem"> <label> 字典名稱:</label> <input id="DictionaryName" name="DictionaryName" type="text" class="required" /></div> <div class="fitem"> <label> 來源:</label> <input id="DictionaryFrom" name="DictionaryFrom" type="text" class="required" /></div> <div class="fitem"> <label> 順序號:</label> <input id="SequenceNumber" name="SequenceNumber" type="text" class="required number" /></div> <div class="fitem"> <label> 描述說明:</label> <input id="Description" name="Description" type="text" class="required" /></div> <div class="fitem"> <label> 字典值:</label> <input id="DictionaryValue" name="DictionaryValue" type="text" class="required" /></div> <div class="fitem"> <label> 類型代碼:</label> <input id="TypeCode" name="TypeCode" type="text" class="required" /></div> <div class="fitem"> <label> 控制等級:</label> <input id="Level" name="Level" type="text" class="required" /></div> <div class="fitem"> <label> 是否禁用:</label> <input id="IsDisabled" name="IsDisabled" type="checkbox" /></div> <input class="btn btn-primary" type="submit" style="width: 80px;" value="提交" id="submit" /> </div> </div> </form> </body> </html>
後臺頁面java
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Data.SqlClient; using System.Data; using Maticsoft.DBUtility; using ECLProduct.Model; using ECLProduct.DAL; namespace WEB.WebSite { /// <summary> /// AD_DATA_DICTIONARY 的摘要說明 /// </summary> public class AD_DATA_DICTIONARY : IHttpHandler { DAL.AD_DATA_DICTIONARY dalADD = new DAL.AD_DATA_DICTIONARY(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string Type = context.Request["type"]; switch (Type) { case "GetPage": int pageindex = int.Parse(context.Request["Pageindex"]); int pagesize = int.Parse(context.Request["PageSize"]); string strwhere = context.Request["searchsName"].ToString(); var tb = GetDataList(pagesize, pageindex, strwhere).Value; //tb = tb.Select(t->); var result=new KeyValuePair<int,string>( GetDataList(pagesize, pageindex, strwhere).Key,JsonHelper.DataTableToJson(tb)); context.Response.Write(JsonHelper.ObjectToJson(result)); break; case "delete": string did=context.Request["data"]; if (delete(did)) { context.Response.Write("刪除成功"); } break; case "Add": try { var model = new ECLProduct.Model.AD_DATA_DICTIONARY() { DictionaryCode = Guid.NewGuid().ToString(), DictionaryName = context.Request["DictionaryName"], DictionaryFrom = context.Request["DictionaryFrom"], DictionaryValue = context.Request["DictionaryValue"], Description = context.Request["Description"], SequenceNumber = int.Parse(context.Request["SequenceNumber"]), TypeCode = context.Request["TypeCode"], Level = int.Parse(context.Request["Level"]), //表單傳過來的radio選中爲on不選爲null IsDisabled = context.Request["IsDisabled"] == "on" ? true : false }; context.Response.Write(AddDictionary(model)); } catch (Exception) { throw; } break; case "modify": try { delete(context.Request["DictionaryCode"]); var model = new ECLProduct.Model.AD_DATA_DICTIONARY() { DictionaryCode = Guid.NewGuid().ToString(), DictionaryName = context.Request["DictionaryName"], DictionaryFrom = context.Request["DictionaryFrom"], Description = context.Request["Description"], DictionaryValue = context.Request["DictionaryValue"], SequenceNumber = int.Parse(context.Request["DictionaryValue"]), TypeCode = context.Request["TypeCode"], Level = int.Parse(context.Request["Level"]), IsDisabled = context.Request["IsDisabled"] == "on" ? true : false }; context.Response.Write(AddDictionary(model)); } catch (Exception) { throw; } break; case "getEditData": string did1 = context.Request["data"]; context.Response.Write(JsonHelper.DataTableToJson(getEditData(did1))); break; } } private KeyValuePair<int, DataTable> GetDataList(int pagesize, int pageindex, string strwhere) { return dalADD.GetList(pagesize, pageindex, strwhere); } private string AddDictionary(ECLProduct.Model.AD_DATA_DICTIONARY model) { if (dalADD.Add(model) > 0) { return "插入成功"; } else return "插入失敗"; } private bool delete(string Did) { return dalADD.Delete(Did); } private bool update(ECLProduct.Model.AD_DATA_DICTIONARY model) { return dalADD.Update(model); } private DataTable getEditData(string Did) { return dalADD.GetList("DictionaryCode='" + Did+"'").Tables[0]; } public bool IsReusable { get { return false; } } } }
json操做類jquery
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Runtime.Serialization.Json; using System.IO; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using System.Collections.Generic; /// <summary> /// JSON序列化和反序列化輔助類 /// </summary> public class JsonHelper { public JsonHelper() { // // TODO: Add constructor logic here // } /// <summary> /// JSON序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// <summary> /// JSON反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public static T JsonDeserializer<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } /// <summary> /// JSON序列化(包含日期格式轉換) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static string JsonSerializer<T>(T t, bool bdate) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); //替換Json的Date字符串 string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); return jsonString; } /// <summary> /// JSON反序列化(包含日期格式轉換) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public static T JsonDeserializer<T>(string jsonString, bool bdate) { //將"yyyy-MM-dd HH:mm:ss"格式的字符串轉爲"\/Date(1294499956278+0800)\/"格式 string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); Regex reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } /// <summary> /// 將Json序列化的時間由/Date(1294499956278+0800)轉爲字符串 /// </summary> /// <param name="m"></param> /// <returns></returns> private static string ConvertJsonDateToDateString(Match m) { string result = string.Empty; DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); result = dt.ToString("yyyy-MM-dd HH:mm:ss"); return result; } /// <summary> /// 將時間字符串轉爲Json時間 /// </summary> /// <param name="m"></param> /// <returns></returns> private static string ConvertDateStringToJsonDate(Match m) { string result = string.Empty; DateTime dt = DateTime.Parse(m.Groups[0].Value); dt = dt.ToUniversalTime(); TimeSpan ts = dt - DateTime.Parse("1970-01-01"); result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds); return result; } /// <summary> /// 將對象轉換爲Json /// </summary> /// <param name="obj">對象</param> /// <returns>Json格式字符串</returns> public static string ObjectToJson(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { throw new Exception("JSonHelp.objectToJson();" + ex.Message); } } /// <summary> /// 數據錶轉鍵值對集合 /// 將DataTable轉成List集合,存每一行 /// </summary> /// <param name="dt">數據表</param> /// <returns>哈希表數組</returns> public static List<Dictionary<string, object>> DataTableToList(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); foreach (DataRow dr in dt.Rows) { Dictionary<string, object> dic = new Dictionary<string, object>(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName]); } list.Add(dic); } return list; } /// <summary> /// 數據集轉鍵值對數組字典 /// </summary> /// <param name="ds">數據集</param> /// <returns>鍵值對數組字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds) { Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>(); foreach (DataTable dt in ds.Tables) { result.Add(dt.TableName, DataTableToList(dt)); } return result; } /// <summary> /// 數據錶轉JSON /// </summary> /// <param name="dt">數據表</param> /// <returns>JSON字符串</returns> public static string DataTableToJson(DataTable dt) { return ObjectToJson(DataTableToList(dt)); } /// <summary> /// 將Json字符串轉換爲對象泛型方法 /// </summary> /// <typeparam name="T">類型</typeparam> /// <param name="JsonText">Json字符串</param> /// <returns>制定類型對象</returns> public static T JsonToObject<T>(string JsonText) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Deserialize<T>(JsonText); } catch (Exception ex) { throw new Exception("JsonHelp.JsonToObject():" + ex.Message); } } /// <summary> /// 將Json字符串轉換爲數據表數據 /// </summary> /// <param name="JsonText">Json文本</param> /// <returns>數據表字典</returns> public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFormJson(string JsonText) { return JsonToObject<Dictionary<string, List<Dictionary<string, object>>>>(JsonText); } /// <summary> /// 將json文本轉換成數據行 /// </summary> /// <param name="JsonText">Json文本</param> /// <returns>數據行的字典</returns> public static Dictionary<string, object> DataRowFormJson(string JsonText) { return JsonToObject<Dictionary<string, object>>(JsonText); } public static DataTable JsonToDataTable(string strJson,string a ) { //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //獲取數據 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split(','); //建立表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { DataColumn dc = new DataColumn(); string[] strCell = str.Split(':'); dc.ColumnName = strCell[0].ToString(); tb.Columns.Add(dc); } tb.AcceptChanges(); } //增長內容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } public static DataTable JsonToDataTableNoFix(string strJson) { //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //獲取數據 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split(','); //建立表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split(':'); dc.ColumnName = strCell[0].Replace("\"", ""); tb.Columns.Add(dc); } tb.AcceptChanges(); } //增長內容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } public static DataTable JsonToDataTable(string strJson) { //取出表名 var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; //去除表名 strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //獲取數據 rg = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split(','); //建立表 if (tb == null) { tb = new DataTable(); tb.TableName = strName; foreach (string str in strRows) { var dc = new DataColumn(); string[] strCell = str.Split(':'); dc.ColumnName = strCell[0]; tb.Columns.Add(dc); } tb.AcceptChanges(); } //增長內容 DataRow dr = tb.NewRow(); for (int r = 0; r < strRows.Length; r++) { dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", ""); } tb.Rows.Add(dr); tb.AcceptChanges(); } return tb; } }
給出效果圖ajax