纯净版crud
首先给出数据库表,很简单只是一张后台数据字典表
分页存储过程
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
列表页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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>
增加和编辑页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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>
后台页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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操作类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; } }
给出效果图