前言
说句心里话,本是此刻才开始对微软MSDN有所感觉,觉得这里才是技术与解决问题的海洋词典。也许从事编程就是这样吧,也不能从一开始学就扎进MSDN,我觉得那样应该会感觉到很累吧,当已经进入到编程世界的时候,接下来再从MSDN也只能从MSDN上汲取养料,我觉得这应该是一条健康学习编程之路吧。
异步通信层示例
Employee类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///Employee 的摘要说明
/// </summary>
public class Employee
{
private string _FirstName;
private string _LastName;
private string _Title;
public Employee() { }
public Employee(string firstName, string lastName, string title)
{
this._FirstName = firstName;
this._LastName = lastName;
this._Title = title;
}
public string FirstName
{
get
{
return this._FirstName;
}
}
public string LastName
{
get
{
return this._LastName;
}
}
public string Title
{
get
{
return this._Title;
}
}
}
GetEmployee.ashx
<%@ WebHandler Language="C#" Class="GetEmployee" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
public class GetEmployee : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string firstName = context.Request.Params["firstName"];
string lastName = context.Request.Params["lastName"];
string title = context.Request.Params["title"];
Employee employee = new Employee(firstName, lastName, title);
//实例化成JSON
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonEmp = serializer.Serialize(employee);
context.Response.Write(jsonEmp);
}
public bool IsReusable {
get {
return false;
}
}
}
AsyncComLayer.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function showEmployee(firstName, lastName, title)
{
var request = new Sys.Net.WebRequest();
request.set_url("GetEmployee.ashx");
request.set_httpVerb("post");
request.add_completed(onGetEmployeeComplete);
var requestBody=String.format("firstName={0}&lastName={1}&title={2}",
encodeURI(firstName),
encodeURI(lastName),
encodeURI(title))
request.set_body(requestBody);
request.invoke();
}
function onGetEmployeeComplete(response)
{
//两个get_没有智能提示,大小写不能出错
if (response.get_responseAvailable()) {
var employee = response.get_object();
alert(String.format("firstName={0},lastName={1},title={2}",
employee.FirstName, //没有智能提示,是大写,也就是类的属性
employee.LastName,
employee.Title));
}
}
</script>
<input type="button" value="Bill Gates"
οnclick="showEmployee('Bill', 'Gates', 'Chair man')" />
<input type="button" value="Steve Ballmer"
οnclick="showEmployee('Steve', 'Ballmer', 'CEO')" />
<div>
</div>
</form>
</body>
</html>
相关的MSDN帮助:http://msdn.microsoft.com/zh-cn/library/bb310979(v=vs.100).aspx