#region DataTable转Json
/// <summary>
/// 将DataTable中的数据转换为JSON字符串,只返回[{...},{...},{...}...]的数据,没有表名
/// </summary>
/// <param name="dt">要转JSON的DataTable</param>
/// <returns></returns>
public static String ToJson(DataTable dt)
{
if (dt != null && dt.Rows.Count > 0 && dt.Columns.Count > 0)
{
StringBuilder _sbRow = new StringBuilder();
StringBuilder _sbCol = new StringBuilder();
foreach (DataRow dr in dt.Rows)
{
if (_sbRow.Length > 0)
_sbRow.Append(",");
_sbRow.Append("{");
foreach (DataColumn dc in dt.Columns)
{
if (_sbCol.Length > 0)
_sbCol.Append(",");
_sbCol.Append(""" + dc.ColumnName + "":"" + dr[dc].ToString() + """);
}
_sbRow.Append(_sbCol);
_sbRow.Append("}");
_sbCol.Length = 0;//将列清空
}
return "[" + _sbRow + "]";
}
return "[]";
}
#endregion
#region list<>转Json
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = list[0].GetType().Name;
Json.Append("{"" + jsonName + "":[");
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = 0; j < pi.Length; j++)
{
Type type = pi[j].GetValue(list[i], null).GetType();
Json.Append(""" + pi[j].Name.ToString() + "":" + """+String.Format(pi[j].GetValue(list[i], null).ToString()+""", type));
if (j < pi.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
#endregion
$.ajax格式
$.ajax({
type: "post",
url: "restTestPage.aspx/sayHi",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'bookName':'" + bookName + "','nowPage':'" + nowPage + "'}",
success: function (data) {
alert(data.d);
//var json = $.parseJSON(data.d);
//$.each(json.jsonName, function (idx, json) {
// alert(json.SSH);
//})
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err=XMLHttpRequest.status;
if (err == '500') {
alert(textStatus);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(XMLHttpRequest.responseText);
}
}
});
list 转 DataTable
[csharp] view plaincopyprint?
List<info> infos = Dal.GetInfos();
DataTable dt = new DataTable();
dt.Columns.Add("cName");
foreach (var info in infos)
{
DataRow dr = dt.NewRow();
dr["cName"] = info.Name;
dt.Add(dr);
}
网上的:
[csharp] view plaincopyprint?
public static class DataTableExtensions
{
/// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(T);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(T);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//创建返回的集合
List<T> oblist = new List<T>();
foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
T ob = new T();
//找到对应的数据 并赋值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTableTow(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/**/
/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
return ToDataTable<T>(list, null);
}
/**/
/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
propertyNameList.AddRange(propertyName);
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
}
-----------------------------------------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentManage.aspx.cs" Inherits="N09_Chapter6.StudentManage" %>
<!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>
<script src="jquery1.8/jquery-1.8.0.js" type="text/javascript"></script>
<script src="jquery1.8/json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btnShowAllStudents").click(function () {
$.ajax({
url: "StudentWebService.asmx/GetAllStudents",
type: "post",
data: {}, //将参数对象转换为字符串
contentType: "application/json",
dataType: "json",
success: function (data) {
var students = data.d;
var result = "<tr><th>学号</th><th>姓名</th><th>性别</th><th>分数</th><th>年龄</th><th>操作</th></tr>";
for (var i = 0; i < students.length; i++) {
result += "<tr>";
result += "<td>" + students[i].StuNo + "</td>";
result += "<td>" + students[i].Name + "</td>";
result += "<td>" + students[i].Sex + "</td>";
result += "<td>" + students[i].Score + "</td>";
result += "<td>" + students[i].Age + "</td>";
result += "<td><a href='#' onclick='getStudentByNo(" + students[i].StuNo + ")'>修改</a>|<a href='#' onclick='deleteStudent(" + students[i].StuNo + ")'>删除</a></td>";
result += "</tr>";
}
$("#tb_students").html(result);
},
error: function () {
alert("ajax请求失败!");
}
});
});
});
//根据学号获取学员信息并填充到修改学员信息的表单元素中
function getStudentByNo(stuNo) {
$("#divOp").show();
$("#txtStuNo").attr("readonly", true);
$("#btnAdd").hide();
$("#btnUpdate").show();
//根据学号查询相应信息
$.ajax({
url: "StudentWebService.asmx/GetStuInfoByStuNo",
type: "post",
data: "{'stuNo':" + stuNo + "}",
contentType: "application/json",
dataType: "json",
success: function (data) {
var result = data.d;
$("#txtStuNo").val(result.StuNo);
$("#txtName").val(result.Name);
$("[name=sex]").each(function (i, data) {
if (data.value == result.Sex) {
data.checked = true;
return;
}
});
$("#txtScore").val(result.Score);
$("#txtAge").val(result.Age);
},
error: function () {
alert("发送ajax请求失败!");
}
});
}
//修改学员信息
function updateStudent() {
var stuNo = $("#txtStuNo").val();
var stuName = $("#txtName").val();
var stuSex = $("[name=sex]:checked").val();
var stuScore = $("#txtScore").val();
var stuAge = $("#txtAge").val();
var stuInfo = { "StuNo": stuNo, "Name": stuName, "Sex": stuSex, "Score": stuScore, "Age": stuAge };
var param = new Object();
param.student = stuInfo;
$.ajax({
url: "StudentWebService.asmx/UpdateStuInfo",
type: "post",
data: JSON.stringify(param),
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data) {
alert("修改成功!");
$("#btnShowAllStudents").click();
} else {
alert("修改失败!");
}
},
error: function () {
alert("发送ajax请求失败!");
}
});
}
//根据学号删除学员信息
function deleteStudent(stuNo) {
if(confirm("确定要删除吗?")){
$.ajax({
url: "StudentWebService.asmx/DeleteStuInfo",
type: "post",
data: "{'stuNo':" + stuNo + "}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data) {
alert("删除成功!");
$("#btnShowAllStudents").click();
} else {
alert("删除失败!");
}
},
error: function () {
alert("发送ajax请求失败!");
}
});
}
}
//显示添加学员的div
function showAddStudentDiv() {
$("#divOp").show();
$("#btnAdd").show();
$("#btnUpdate").hide();
$("#txtStuNo").val("");
$("#txtName").val("");
$("[name=sex]:eq(0)").attr("checked", true);
$("#txtScore").val("");
$("#txtAge").val("");
}
//添加学员信息
function addStudent() {
var stuNo = $("#txtStuNo").val();
var stuName = $("#txtName").val();
var stuSex = $("[name=sex]:checked").val();
var stuScore = $("#txtScore").val();
var stuAge = $("#txtAge").val();
var stuInfo = { "StuNo": stuNo, "Name": stuName, "Sex": stuSex, "Score": stuScore, "Age": stuAge };
var param = new Object();
param.student = stuInfo;
$.ajax({
url: "StudentWebService.asmx/AddStudent",
type: "post",
data: JSON.stringify(param),
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data) {
alert("添加成功!");
$("#btnShowAllStudents").click();
} else {
alert("添加失败!");
}
},
error: function () {
alert("发送ajax请求失败!");
}
});
}
//根据性别查询学员信息
function selectStuInfoBySex() {
var sex = $("#selSex").val();//获取选中的性别
$.ajax({
url: "StudentWebService.asmx/GetStuInfoBySex",
type: "post",
data: "{'sex':'" + sex + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
var students = data.d;
var result = "<tr><th>学号</th><th>姓名</th><th>性别</th><th>分数</th><th>年龄</th><th>操作</th></tr>";
for (var i = 0; i < students.length; i++) {
result += "<tr>";
result += "<td>" + students[i].StuNo + "</td>";
result += "<td>" + students[i].Name + "</td>";
result += "<td>" + students[i].Sex + "</td>";
result += "<td>" + students[i].Score + "</td>";
result += "<td>" + students[i].Age + "</td>";
result += "<td><a href='#' onclick='getStudentByNo(" + students[i].StuNo + ")'>修改</a>|<a href='#' onclick='deleteStudent(" + students[i].StuNo + ")'>删除</a></td>";
result += "</tr>";
}
$("#tb_students").html(result);
},
error: function () {
alert("发送ajax请求失败!");
}
});
}
</script>
</head>
<body>
<input type="button" value="显示所有学员信息" id="btnShowAllStudents" />
性别:
<select id="selSex" onchange="selectStuInfoBySex()">
<option>--请选择性别--</option>
<option value="男">男</option>
<option value="女">女</option>
</select>
<table id="tb_students" border="1">
</table>
<input type="button" value="添加学员信息" id="btnAddStudent" onclick="showAddStudentDiv()"/>
<div id="divOp" style="border:1px solid gray; 500px; height:100px;display:none">
<form id="stuForm">
学号:<input type="text" id="txtStuNo"/>
姓名:<input type="text" id="txtName" /><br />
性别:<input type="radio" name="sex" value="男" checked/>男<input type="radio" name="sex" value="女"/>女<br />
成绩:<input type="text" id="txtScore" />
年龄:<input type="text" id="txtAge"/><br />
<input type="button" value="添加" id="btnAdd" onclick="addStudent()"/>
<input type="button" value="修改" id="btnUpdate" onclick="updateStudent()"/>
</form>
</div>
</body>
</html>
------------------------------asmx----------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace N09_Chapter6
{
/// <summary>
/// StudentWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class StudentWebService : System.Web.Services.WebService
{
/// <summary>
/// 获取所有学员信息
/// </summary>
/// <returns></returns>
[WebMethod]
public List<StuInfo> GetAllStudents()
{
JqueryDBDataContext db = new JqueryDBDataContext();
return db.StuInfo.ToList();
}
/// <summary>
/// 添加学员信息
/// </summary>
/// <param name="student">学员对象</param>
/// <returns></returns>
[WebMethod]
public bool AddStudent(StuInfo student)
{
try
{
JqueryDBDataContext db = new JqueryDBDataContext();
db.StuInfo.InsertOnSubmit(student);
db.SubmitChanges();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 根据学号获取学员信息
/// </summary>
/// <param name="stuNo">学号</param>
/// <returns></returns>
[WebMethod]
public StuInfo GetStuInfoByStuNo(int stuNo)
{
JqueryDBDataContext db = new JqueryDBDataContext();
return db.StuInfo.FirstOrDefault(s=>s.StuNo==stuNo);
}
/// <summary>
/// 修改学员信息
/// </summary>
/// <param name="student">学员信息</param>
/// <returns></returns>
[WebMethod]
public bool UpdateStuInfo(StuInfo student)
{
try
{
JqueryDBDataContext db = new JqueryDBDataContext();
StuInfo stu = db.StuInfo.FirstOrDefault(s => s.StuNo == student.StuNo);
stu.Name = student.Name;
stu.Sex = student.Sex;
stu.Age = student.Age;
stu.Score = student.Score;
db.SubmitChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
/// <summary>
/// 删除学员信息
/// </summary>
/// <param name="stuNo">学号</param>
/// <returns></returns>
[WebMethod]
public bool DeleteStuInfo(int stuNo)
{
try
{
JqueryDBDataContext db = new JqueryDBDataContext();
StuInfo stu = db.StuInfo.FirstOrDefault(s => s.StuNo == stuNo);
db.StuInfo.DeleteOnSubmit(stu);
db.SubmitChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
/// <summary>
/// 根据性别获取学员信息
/// </summary>
/// <param name="sex"></param>
/// <returns></returns>
[WebMethod]
public List<StuInfo> GetStuInfoBySex(string sex)
{
JqueryDBDataContext db = new JqueryDBDataContext();
return db.StuInfo.Where(s=>s.Sex.ToString()==sex).ToList();
}
}
}
------------------------------------------------