转载自:http://www.cnblogs.com/chenxizhang/archive/2010/01/30/1659979.html
AJAX的应用程序,免不了经常需要在页面和服务之间异步传输数据。我已经多次写过这方面的东西。下面还是有一个比较经典的案例,我认为掌握到这些,那么处理异步请求的时候就相当方便了。
第一部分:客户端页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication1.WebForm3" %>
<!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>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
//构造一个json对象,很类似于C#中的匿名类型
var employee = {
Name: "chenxizhang",
Country: "China",
Orders: [
{ OrderID: 10248 },
{ OrderID: 10249 }
]
};
//发送POST请求,数据也是json格式。但数值部分需要转换为字符串
$.post("EmployeeHandler.ashx", { data: JSON.stringify(employee) }, function(result) {
var r = JSON.parse(result);
alert(r.Message);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
第二部分:ashx部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
//必须添加System.ServiceModel.Web和System.Runtime.Serialization的引用
namespace WebApplication1
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class EmployeeHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var ser = new DataContractJsonSerializer(typeof(Employee));
var data = context.Request["data"];
var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
var emp = (Employee)ser.ReadObject(ms);
ms.Close();
//此时已经得到了相应的Employee实例,可以进行服务器端的处理
var ser2 = new DataContractJsonSerializer(typeof(ActionResult));
var ms2 = new MemoryStream();
var result = new ActionResult() { Code = 200, Message = "成功" };
ser2.WriteObject(ms2, result);
ms2.Position = 0;
var buffer = new byte[ms2.Length];
ms2.Read(buffer, 0, buffer.Length);
ms2.Close();
context.Response.Write(Encoding.UTF8.GetString(buffer));
//返回结果
}
public bool IsReusable
{
get
{
return false;
}
}
}
[DataContract]
public class Employee {
[DataMember]
public string Name { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public OrderItem[] Orders { get; set; }
}
[DataContract]
public class OrderItem
{
[DataMember]
public int OrderID { get; set; }
}
[DataContract]
public class ActionResult
{
[DataMember]
public int Code { get; set; }
[DataMember]
public string Message { get; set; }
}
}
第三部分:进一步的优化,编写两个扩展方法(这是C# 3.0的新特性)
/// <summary>
/// 这个类型实现了对JSON数据处理的一些扩展方法
/// </summary>
public static class JsonExtensions
{
/// <summary>
/// 根据一个字符串,进行JSON的反序列化,转换为一个特定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static T ToJsonObject<T>(this string data) {
var serializer = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(
Encoding.UTF8.GetBytes(data));
var result = (T)serializer.ReadObject(ms);
ms.Close();
return result;
}
/// <summary>
/// 将任何一个对象转换为JSON字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonString<T>(this T obj) {
var serializer = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
serializer.WriteObject(ms, obj);
ms.Position = 0;
var result = Encoding.UTF8.GetString(ms.GetBuffer());
ms.Close();
return result;
}
}
这样,在ashx里面的代码就很简单了
var emp = context.Request["data"].ToJsonObject<Employee>();
var result = new ActionResult() { Code = 200, Message = "成功" };
context.Response.Write(result.ToJsonString());
不错吧,这样以后处理Json就是如此容易
通过Json来传递数据,可以避免以前用传统的post或者get方面拼接字符串中的麻烦