JQuery将DataTable list<>数据转换成JSON数据 动态创建表格显示数据
一般处理程序JsonDate.ashx
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
DataTable data2 = myData();
string str = DataTableToJson("myJson", data2);//构建的json数据
context.Response.Write(str);
}
public bool IsReusable
{
get
{
return false;
}
}
//用datatable做数据,数据模拟
public DataTable myData()
{
DataTable dt = new DataTable();
DataColumn dc;
DataRow dr;
dc = new DataColumn("Name", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Email", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Phon", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Move", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Pan", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("select", System.Type.GetType("System.String"));
dt.Columns.Add(dc);
for (int i = 1; i < 7; i++)
{
dr = dt.NewRow();
dr["Name"] = "Name" + i.ToString();
dr["Email"] = "Email" + i.ToString();
dr["Phon"] = "Phon" + i.ToString();
dr["Move"] = "Move" + i.ToString();
dr["Pan"] = "Pan" + i.ToString();
dr["select"] = i.ToString();
dt.Rows.Add(dr);
}
int count = dt.Rows.Count;
return dt;
}
//将datatable数据转换成JSON数据
public string DataTableToJson(string jsonName, DataTable dt)
{
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Json.Append(dt.Columns[j].ColumnName.ToString() + ":\"" + dt.Rows[i][j].ToString() + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
}
//列表数据转换到json数据
public string ObjectToJson<T>(string jsonName, IList<T> IL)
{
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (IL.Count > 0)
{
for (int i = 0; i < IL.Count; i++)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
Json.Append(pis[j].Name.ToString() + ":\"" + pis[j].GetValue(IL[i], null) + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < IL.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString();
}
页面Default.aspx
function GetData()
{
$.getJSON(
"JsonData.ashx",//产生Json数据的服务端页面
function(json)
{
for(var i=0;i<json.length;i++)
{
//开始
var index=-1;
var txtTRLastIndex = findObj("txtTRLastIndex",document);
var rowID = parseInt(txtTRLastIndex.value);
var signFrame = findObj("SignFrame",document);
//添加行
var newTR = signFrame.insertRow(signFrame.rows.length);
newTR.id = "SignItem" + rowID;
//添加列:序号
var newNameTD=newTR.insertCell(0);
//添加列内容
newNameTD.innerHTML = newTR.rowIndex.toString();
//添加列:姓名
var newNameTD=newTR.insertCell(1);
//添加列内容
newNameTD.innerHTML = "<input name='txtName" + rowID + "' id='txtName" + rowID + "' value='"+json[i].Name+"' type='text' size='12' />";
//添加列:电子邮箱
var newEmailTD=newTR.insertCell(2);
//添加列内容
newEmailTD.innerHTML = "<input name='txtEMail" + rowID + "' id='txtEmail" + rowID + "' value='"+json[i].Email+"' type='text' size='20' />";
//添加列:电话
var newTelTD=newTR.insertCell(3);
//添加列内容
newTelTD.innerHTML = "<input name='txtTel" + rowID + "' id='txtTel" + rowID + "' value='"+json[i].Phon+"' type='text' size='10' />";
//添加列:手机
var newMobileTD=newTR.insertCell(4);
//添加列内容
newMobileTD.innerHTML = "<input name='txtMobile" + rowID + "' id='txtMobile" + rowID + "' value='"+json[i].Move+"' type='text' size='12' />";
//添加列:公司名
var newCompanyTD=newTR.insertCell(5);
//添加列内容
newCompanyTD.innerHTML = "<input name='txtCompany" + rowID + "' id='txtCompany" + rowID + "' value='"+json[i].Pan+"' type='text' size='20' />";
//添加下拉框
var newCompanyTD=newTR.insertCell(6);
newCompanyTD.innerHTML = "<select id='Select"+rowID+"'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option> </select>";
//动态选中下拉框
for(var j=0;j<document.getElementById("Select"+rowID).options.length;j++)
{
if(document.getElementById("Select"+rowID).options[j].text==json[i].select)
index=j;
}
if(index>=0)
document.getElementById("Select"+rowID).options[index].selected=true;
//添加列:删除按钮
var newDeleteTD=newTR.insertCell(7);
//添加列内容
newDeleteTD.innerHTML = "<div align='center' style='width:40px'><a href='javascript:;' onclick=\"DeleteSignRow('SignItem" + rowID + "')\">删除</a></div>";
//将行号推进下一行
txtTRLastIndex.value = (rowID + 1).toString();
}
}
)
}
-----------------------------------------------------
---------------------------------------------------
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// 将DataTable或Ilist<>转换成JSON格式
/// </summary>
public class ToJson
{
public ToJson()
{
}
//DataTable转成Json
public static string DataTableToJson(string jsonName, DataTable dt)
{
StringBuilder Json = new StringBuilder();
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
//List转成json
public static string ObjectToJson<T>(string jsonName, IList<T> IL)
{
StringBuilder Json = new StringBuilder();
Json.Append("{\"" + jsonName + "\":[");
if (IL.Count > 0)
{
for (int i = 0; i < IL.Count; i++)
{
T obj = Activator.CreateInstance<T>();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < IL.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
}
2各种数据集转换为json/// <summary>
/// 对象转换为Json字符串
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string jsonString = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
string value = string.Empty;
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
else if(objectValue is string)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
else if (objectValue is IEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());
}
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
}
return Json.DeleteLast(jsonString) + "}";
}
/// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += Json.ToJson(item) + ",";
}
return Json.DeleteLast(jsonString) + "]";
}
/// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
return Json.DeleteLast(jsonString) + "]";
}
/// <summary>
/// 删除结尾字符
/// </summary>
/// <param name="str">需要删除的字符</param>
/// <returns>完成后的字符串</returns>
private static string DeleteLast(string str)
{
if (str.Length > 1)
{
return str.Substring(0, str.Length - 1);
}
return str;
}
/// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable table)
{
string jsonString = "[";
DataRowCollection drc = table.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString += "{";
foreach (DataColumn column in table.Columns)
{
jsonString += "\"" + ToJson(column.ColumnName) + "\":";
if (column.DataType == typeof(DateTime) || column.DataType == typeof(string))
{
jsonString += "\"" + ToJson(drc[i][column.ColumnName].ToString()) + "\",";
}
else
{
jsonString += ToJson(drc[i][column.ColumnName].ToString()) + ",";
}
}
jsonString = DeleteLast(jsonString) + "},";
}
return DeleteLast(jsonString) + "]";
}
/// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DbDataReader dataReader)
{
string jsonString = "[";
while (dataReader.Read())
{
jsonString += "{";
for (int i = 0; i < dataReader.FieldCount; i++)
{
jsonString += "\"" + ToJson(dataReader.GetName(i)) + "\":";
if (dataReader.GetFieldType(i) == typeof(DateTime) || dataReader.GetFieldType(i) == typeof(string))
{
jsonString += "\"" + ToJson(dataReader[i].ToString()) + "\",";
}
else
{
jsonString += ToJson(dataReader[i].ToString()) + ",";
}
}
jsonString = DeleteLast(jsonString) + "}";
}
dataReader.Close();
return DeleteLast(jsonString) + "]";
}
/// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + ToJson(table.TableName) + "\":" + ToJson(table) + ",";
}
return jsonString = DeleteLast(jsonString) + "}";
}
/// <summary>
/// String转换为Json
/// </summary>
/// <param name="value">String对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
string temstr;
temstr = value;
temstr = temstr.Replace("{", "{").Replace("}", "}").Replace(":", ":").Replace(",", ",").Replace("[", "【").Replace("]", "】").Replace(";", ";").Replace("\n", "<br/>").Replace("\r", "");
temstr = temstr.Replace("\t", " ");
temstr = temstr.Replace("'", "\'");
temstr = temstr.Replace(@"\", @"\\");
temstr = temstr.Replace("\"", "\"\"");
return temstr;
}