一、引言
在ASp.NET網頁的默認模型中,用戶通過單擊按鈕或其他操作的方式來提交頁面,此時客戶端將當前頁面表單中的所有數據(包括一些自動生成的隱藏域)都提交到服務器端,服務器將重新實例化一個當前頁面類的實例來響應這個請求,然后將整個頁面的內容重新發送到客戶端。這種處理方式對運行結果沒什么影響,但頁回發會導致處理開銷,從而降低性能,且會讓用戶不得不等待處理并重新創建頁,有時候,我們僅僅只需要傳遞部分數據而不需要提交整個表單,這種默認的處理方式(指的是提交整個表單進行回發方式)顯得有點小題大做了,解決辦法主要有三種: 純 JS實現、 Ajax技術和回調技術,在這里僅僅介紹下Asp.net回調技術的實現。(回調的本質其實就是Ajax調用,之所以這么說是因為我們使用Asp.net中的類來實現回調,Asp.net中類會幫我們做Ajax的操作)。
二、實現步驟
使用回調技術來實現無刷新頁面的要點是:
1、讓當前頁面實現ICallbackEventHandler接口,該接口定義了兩個方法:GetCallbackResult 方法和RaiseCallbackEvent方法,其中,GetCallbackResult方法的作用是返回以控件為目標的回調方法的結果;RaiseCallbackEvent方法是處理以控件為目標的回調方法.
2、為當前頁面提供2個JS腳本,一個是客戶端調用服務器端方法成功后要執行的客戶端方法,一個是客戶端調用服務器端方法失敗后要執行的客戶端方法。
具體測試頁面代碼為:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="ASPNETClientCallBackWithoutPostBack.Register" %>
<!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">
// 調用服務器端成功時調用的客戶端方法
function Success(arg, context) {
document.getElementById("message").innerHTML = arg;
}
// 調用服務器端失敗時調用的客戶端方法
function Error(arg, context) {
document.getElementById("message").innerHTML = "發生異常";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
用戶名:
<input type="text" id="txtUserName" onblur="CallServerMethod(txtUserName.value,null)" />
<span id="message" style="color:Red"></span>
</div>
<div>
密碼:
<input type="text" id="txtpassword" style="margin-left:15px" />
</div>
</div>
</form>
</body>
</html>
后臺CS代碼為:
using System;
using System.Web.UI;
namespace ASPNETClientCallBackWithoutPostBack
{
public partial class Register : System.Web.UI.Page, ICallbackEventHandler
{
string result=string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
// 獲得當前頁的ClientScriptManager對象,該對象用于管理客戶端腳步
ClientScriptManager clientScriptManager = Page.ClientScript;
// 獲取回調引用
// 執行下面代碼會在客戶端生成WebForm_DoCallback方法,調用他來達到異步調用,這個方法是ASP.NET自動生成的方法,會被發送到客戶端
string reference = clientScriptManager.GetCallbackEventReference(this, "arg", "Success", "", "Error", true);
string callBackScript = "function CallServerMethod(arg, context){" + reference + ";}";
// 向當前頁面注冊客戶端腳本
// CallServerMethod是要注冊的客戶端腳本的鍵
clientScriptManager.RegisterClientScriptBlock(this.GetType(), "CallServerMethod", callBackScript, true);
}
/// <summary>
/// 服務器端運行的回調方法
/// </summary>
/// <param name="eventArgument"></param>
public void RaiseCallbackEvent(string eventArgument)
{
if (eventArgument.ToLower().IndexOf("admin") != -1)
{
result = eventArgument + "用戶已注冊";
}
else
{
result = eventArgument + "可以注冊";
}
}
/// <summary>
/// 返回回調方法的執行結果
/// </summary>
public string GetCallbackResult()
{
return result;
}
}
}
當我們在瀏覽器中查看上面Asp.net頁面時,Asp.net頁面會經過服務器端Page類的處理生成標準的HTML代碼,具體代碼如下:
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>
用戶注冊
</title>
<script language="javascript">
// 調用服務器端成功時調用的客戶端方法
function Success(arg, context) {
document.getElementById("message").innerHTML = arg;
}
// 調用服務器端失敗時調用的客戶端方法
function Error(arg, context) {
document.getElementById("message").innerHTML = "發生異常";
}
</script>
</head>
<body>
<form method="post" action="Register.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="">
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzgzNDMwNTMzZGRhQnkA8wRg1s7uEiDb6xwTLc8yV3cMvxUYSRtK9Yaw9Q==">
</div>
// 在生成的HTML代碼中多了幾段JS代碼塊
// 這部分代碼是每個Asp.net頁面發送到客戶端都會生成的,用于提交當前表單
// eventTarget表示激發提交時間的控件,eventArgument表示發生該事件時的參數信息,他們的值都可以通過Debug的方式進行查看
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
// 這部分代碼用來生成用于Ajax調用的JS腳本,其源碼中有WebForm_DoCallback方法的定義
<script src="/WebResource.axd?d=Okp1JZTDECHos0RqI93uiUGmigRVKnpI1GrXTy8FPFuLgF3yEpwKfV7V477WPUrfAxs2eKT9i4LoIZ4cWS-poziKdbgOx1EKoRZYERcCJOs1&t=634714073180000000" type="text/javascript"></script>
// 這部分代碼是由服務端代碼生成的,因為我們在后臺代碼中使用ClientScriptManager.RegisterClientScriptBlock方法來注冊一段前端腳本
<script type="text/javascript">
//<![CDATA[
function CallServerMethod(arg, context){WebForm_DoCallback('__Page',arg,Success,"",Error,true);}//]]>
</script>
<div>
<div>
用戶名:
<input type="text" id="txtUserName" onblur="CallServerMethod(txtUserName.value,null)">
<span id="message" style="color:Red"></span>
</div>
<div>
密碼:
<input type="text" id="txtpassword" style="margin-left:15px">
</div>
</div>
// WebForm——InitCallback方法的定義也在幕后生成的腳本文件中,腳本代碼可以在Chorme的Source選項卡中找到。
<script type="text/javascript">
//<![CDATA[
WebForm_InitCallback();//]]>
</script>
</form>
</body></html>
四、小結
因為最近一段時間在學習Asp.net的內容,這里記錄下一些學習過程中個人覺得比較重要的內容,希望對其他一些朋友有所幫助。