这个例子是为了解答一个网友的问题而写的。使用场景就是,希望在ashx中返回DataTable,然后在页面中进行异步调用和显示。原先他的做法是想用json格式返回数据。
因为DataTable可以直接序列化为XML格式,所以我比较推荐用XML返回。而不是再去解析为json之类的格式。
1. 创建ashx文件
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
namespace WebApplication1
{
///
/// $codebehindclassname$ 的摘要说明
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GetData : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
context.Response.Charset = "UTF-8";
DataTable dt = new DataTable("Employees");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
for (int i = 0; i < 50; i++)
{
DataRow row = dt.NewRow();
row[0] = i;
row[1] = "员工"+i.ToString();
dt.Rows.Add(row);
}
dt.WriteXml(context.Response.OutputStream);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
这个文件如果直接访问的话,是类似下面这样的返回结果
2.编写页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
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="jquery-1.3.2-vsdoc.js" type="text/javascript">
script>