DataTable/集合 转 Json
前端用的jqueryUI框架获取json格式数据绑定显示表格。
后端通过WebService获取的数据是DataTable。
现将获取DataTable转Json,也支持将数据集合转Json。
一。项目中引用:Newtonsoft.Json
二。功能代码,很简单:
using System;
using System.Data;
namespace WebApplication1.Common
{
public class DataTableToModel
{
public static DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
dt.Rows.Add(1, "Satinder Singh", "Bsc Com Sci", "Mumbai");
dt.Rows.Add(2, "Amit Sarna", "Mstr Com Sci", "Mumbai");
dt.Rows.Add(3, "Andrea Ely", "Bsc Bio-Chemistry", "Queensland");
dt.Rows.Add(4, "Leslie Mac", "MSC", "Town-ville");
dt.Rows.Add(5, "Vaibhav Adhyapak", "MBA", "New Delhi");
return dt;
}
///
/// 用于视图层数据表绑定信息
///
///
public class ViewBaseModel
{
public int total { get; set; }
public int page { get; set; }
public int records { get; set; }
public T rows { get; set; }
}
///
/// 将DataTable中指定列数据 转 Json
///
///
///
///
///
public static string Convert
return Newtonsoft.Json.JsonConvert.SerializeObject(dataList);
}
///
/// 将DataTable中指定列数据 转 Json
///
/// 总页数
/// 指定页序号,起始为1
/// 数据总数
/// 数据集合
/// 显示DataTable中指定列
///
public static string ConvertTable(int total, int page, int records, DataTable dTable, params string[] columnNames) {
if (dTable == null || dTable.Rows.Count <= 0)
{
return string.Empty;
}
if (columnNames != null && columnNames.Length > 0)
{
dTable = dTable.DefaultView.ToTable(false, columnNames);
}
return ConvertCollection(total, page, records, dTable);
}
///
/// 将数据集合 转 Json
///
///
/// 总页数
/// 指定页序号,起始为1
/// 数据总数
/// 类型集合对象
///
public static string ConvertCollection
{
if (dataCollection == null)
{
return string.Empty;
}
var jsonModel = new ViewBaseModel
jsonModel.page = page;
jsonModel.records = records;
jsonModel.total = total;
jsonModel.rows = dataCollection;
return Newtonsoft.Json.JsonConvert.SerializeObject(jsonModel);
}
}
}
三。外部调用:
1.
DataTable dtable = Common.DataTableToModel.GetData();
if (dtable == null || dtable.Rows.Count <= 0)
{
return View();
}
DataTable newTable = dtable.DefaultView.ToTable(false, "UserName");
var jsonModel = new Common.DataTableToModel.ViewBaseModel
jsonModel.page = 1;
jsonModel.records = 1200;
jsonModel.total = 100;
jsonModel.rows = newTable;
ViewBag.Data = Common.DataTableToModel.Convert(jsonModel);
2.
ViewBag.Data = Common.DataTableToModel.ConvertTable(1, 1, 1, Common.DataTableToModel.GetData());
3.
public class dataRows {
public int sid { get; set; }
public string uname { get; set; }
public DateTime addTime { get; set; }
}
var drList = new List
new dataRows() { addTime=DateTime.Now, sid=1, uname="test111"},
new dataRows() { addTime=DateTime.Now, sid=2, uname="test222"},
new dataRows() { addTime=DateTime.Now, sid=3, uname="test333"}
};
ViewBag.Data = Common.DataTableToModel.ConvertCollection>(1, 1, 1,drList);