使用案例:將頁面easy ui 中datagrid表格中的數據,存成json字符串,
通過ajax和ashx傳入C#將string類型的json字符串解析成list<>泛型集合,
由於業務需要,將本地sql不同表的數據和頁面html的數據(通過webservice傳入),放在一起處理數據。
轉化方法:
public class ListToDatatable { public ListToDatatable() { } public static DataTable ListToDataTable<T>(List<T> entitys) { //檢查實體集合不能為空 if (entitys == null || entitys.Count < 1) { return new DataTable(); } //取出第一個實體的所有Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生產代碼中,應將生成的DataTable結構Cache起來,此處略 DataTable dt = new DataTable("dt"); for (int i = 0; i < entityProperties.Length; i++) { //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType); dt.Columns.Add(entityProperties[i].Name); } //將所有entity添加到DataTable中 foreach (object entity in entitys) { //檢查所有的的實體都為同一類型 if (entity.GetType() != entityType) { throw new Exception("要轉換的集合元素類型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; } }
1、頁面代碼
var rows = $('#tb_Master').datagrid('getRows'); this.dataArray = new Array(); for (this.i = 0; i < rows.length; i++) { this.model = { PT_PCURR: rows[i].PT_PCURR, MATNR: rows[i].MATNR } dataArray.push(model); } var json = $.toJSON(dataArray);
會得到如下一個json字符串 [{"PT_PCURR":"1.00","MATNR":"8"},{"PT_PCURR":"0.80","MATNR":"8"},{"PT_PCURR":"-0.20","MATNR":"8"}]
2、將string轉化為list<>泛型集合
List<DDMX> listMX = null; if (!string.IsNullOrEmpty(param[1])) { listMX = Tools.JSONTools.JSONStringToList<DDMX>(param[1]); } [Serializable] //這個實體類,自由創建,根據你前台頁面傳入的實體類形式 class DDMX { private string _matnr; private decimal _pt_pcurr; public decimal PT_PCURR { set { _pt_pcurr = value; } get { return _pt_pcurr; } } public string MATNR { set { _matnr = value; } get { return _matnr; } } }
有需要 JSONStringToList 方法的朋友可以給我留言,也可自己網上搜搜
3、將list<>集合轉化為 DataTable
DataTable dt = new DataTable(); dt = ListToDatatable.ListToDataTable(listMX);