在使用JQery的Ajax功能時經常要擷取資料,而Net中擷取的資料經常方便的就是DataTable
而JQuery要Json格式:這樣就是轉換可以利用以下這個方法進行
/// <summary>
/// DataTable轉成Json資料
/// </summary>
public static class DataTableToJSON
{
/// <summary>
/// 將dt轉化成Json資料 格式如 table[{id:1,title:'體育'},id:2,title:'娛樂'}]
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DtToSON(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("recordcount:" + dt.Rows.Count + ",table: [");
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i > 0)
jsonBuilder.Append(",");
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j > 0)
jsonBuilder.Append(",");
jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("\t", " ").Replace("\r", " ").Replace("\n", " ").Replace("\'", "\\\'") + "'");
}
jsonBuilder.Append("}");
}
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
}
/////////////////////////////////////////////前台jqery如何使用請看下面的實現方法//////////////////////////////////////////////////
前台頁面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClassNameByJSON.aspx.cs" Inherits="ClassName" %>
<!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 language="javascript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
$("#DropDownList1").change(function(){
//擷取值測試
// alert($("#DropDownList1").val());
//ajax擷取資料
$("#DropDownList2").html("");
$("#DropDownList2").append("<option value=\"0\">--請選擇學生--</option>");
$.get("GetStudent.ashx",{action:"get",className:$("#DropDownList1").val()},function(data){
//伺服器處理後執行,資料由data傳回
var jsJosn=eval('('+data+')');
//alert(jsJosn.stuentscount);
//alert(jsJosn.stuents[0].stuName);
for(var i=0;i<jsJosn.stuentscount;i++){
$("#DropDownList2").append("<option value=\""+jsJosn.stuents[i].id+"\">"+jsJosn.stuents[i].stuName+"</option>");
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
DataTextField="ClassName" DataValueField="Id" Width="183px" AppendDataBoundItems="True">
<asp:ListItem Value="0">--請選擇班級--</asp:ListItem>
</asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AjaxDemoConnectionString %>"
SelectCommand="SELECT * FROM [ClassInfo]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True" Width="168px">
<asp:ListItem Value="0">-請選擇學生-</asp:ListItem>
</asp:DropDownList></div>
</form>
</body>
</html>
擷取資料利用.ashx檔案
<%@ WebHandler Language="C#" class="GetStudent" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
public class GetStudent : IHttpHandler {
//通過請求擷取學生,返回json對象
public void ProcessRequest (HttpContext context) {
string classVale = context.Request.Params["className"];
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = @"server=CB2E66F752294E9\SQLEXPRESS;database=ajaxdemo;uid=sa;pwd=sa";
SqlCommand sqlcomm = new SqlCommand();
sqlcomm.Connection = sqlconn;
sqlcomm.CommandText = "select * from dbo.StudentInfo where ClassId=" + int.Parse(classVale);
SqlDataAdapter adp = new SqlDataAdapter(sqlcomm);
DataSet set = new DataSet();
adp.Fill(set);
//封裝成JSON格式
//例如:{stuentscount:10,stuents:[{id:1,stuName:"張三"},{id:2,stuName:"李四"}]}
if (set.Tables[0].Rows.Count == 0)
{
context.Response.Write("0");
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("{stuentscount:"+set.Tables[0].Rows.Count+",stuents:[");
for (int i = 0; i < set.Tables[0].Rows.Count; i++)
{
sb.Append("{id:" + set.Tables[0].Rows[i]["Id"].ToString() + ",stuName:\""+set.Tables[0].Rows[i]["StudentName"].ToString()+"\"}");
if (i != set.Tables[0].Rows.Count - 1) {
sb.Append(",");
}
}
sb.Append("]}");
context.Response.Write(sb.ToString());
}
}
public bool IsReusable {
get {
return false;
}
}
}
#Jquery