最近開始學習ASP.Net AJax 搞了兩天學了點皮毛,貼點代碼 日後方便自己查看
客戶端:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ASP.NetA_JAX.ASPx.cs" Inherits="_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 type="text/JScript">
function CallServer() {
//JSON發送對象
ServerSum("{name:'linyijia',age:'21'}");
}
function GetRegister(rg, contex) {
document.getElementById("TxtRegister").value=rg;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
用戶名:<input id="TxtNum1" type="text" />
<br />
服務器:<input id="TxtRegister" type="text" /><br />
<button id="SumBtn" type="button" onclick="CallServer()">登錄</button>
</div>
</form>
</body>
</Html>
服務器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
public partial class _Default : System.Web.UI.Page ,ICallbackEventHandler
{
Users u = null;
protected void Page_Load(object sender, EventArgs e)
{
//回調GetRegister方法
string CallBackFun = Page.ClIEntScript.GetCallbackEventReference(this,"arg","GetRegister","context");
//創建ServerSum方法,在客戶端調用的時候就,會回調GetRegister方法,把參數傳給RaiseCallbackEvent(string eventArgument ),最後通過
//GetCallbackResult()方法把返回值傳給客戶端
string RegisterFun = string.Format("function ServerSum(arg,context){{{0};}}",CallBackFun);
Page.ClientScript.RegisterClIEntScriptBlock(this.GetType(),"ServerSum",RegisterFun,true);
}
string mssage = string.Empty;
#region ICallbackEventHandler 成員
public string GetCallbackResult()
{
return "服務器:你好,你的用戶名為:" + u.Name + "你的年齡為" + u.Age;
}
public void RaiseCallbackEvent(string eventArgument)
{
JavascriptSerializer JS = new JavaScriptSerializer();
u =JS.Deserialize<Users>(eventArgument);
}
#endregion
}
Users類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///User 的摘要說明
/// </summary>
public class Users
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
string age;
public string Age
{
get { return age; }
set { age = value; }
}
}
原理:
使用JSON向服務器發送一個對象,服務器通過實現 ICallbackEventHandler接口後,重寫GetCallbackResult和RaiseCallbackEvent方法,在回調的時候,在RaiseCallbackEvent方法
中反序列化JSON,並在GetCallbackResult把結果返回給客戶端.具體的我以後有空再補充,歡迎大家討論!