程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> ASP.NET 2.0中控件的簡單異步回調

ASP.NET 2.0中控件的簡單異步回調

編輯:關於ASP.NET

雖然已經有了ASP.NET AJAX了,最近學習ASP.NET控件的時候,逐步理解了原始的控件異步回調(代碼取自《ASP.NET 2.0 高級編程》):

首先,在Render事件中添加好一個事件

protected override void RenderContents(HtmlTextWriter output)
{
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
output.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID);
output.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
output.AddAttribute("OnBlur", "ClientCallback();");
this.AddAttributesToRender(output);
output.RenderBeginTag(HtmlTextWriterTag.Input);
output.RenderEndTag();
output.RenderEndTag();
}

這裡最重要的就是output.AddAttribute("OnBlur","ClientCallback();");

然後在OnPreRender事件中,添加如下代碼:protected override void OnPreRender(EventArgs e)
{
//Page.ClientScript.RegisterClientScriptInclude("UtilityFunctions", "JScript.js");
Page.ClientScript.RegisterStartupScript(typeof(Page), "ControlFocus", "document.getElementById('" + this.ClientID + "').focus();", true);
Page.ClientScript.RegisterStartupScript(typeof(Page),"ClientCallback","function ClientCallback() {"+"args=document.getElementById('"+this.ClientID+"').value;"+Page.ClientScript.GetCallbackEventReference(this,"args","CallbackHandler",null,"ErrorHandler",true)+"}");
//向服務器發送請求,由服務器端生成回調的客戶端腳本。
}

也就是在服務器端生成客戶端代碼,注意最後一個方法GetCallbackEventReference,我理解的是在服務器端捕捉了客戶端的請求之後,生成相應的客戶端腳本,在服務器端回調的時候,客戶端決定用什麼函數處理回調和錯誤。

服務器端實現接口的一個方法,也就是接收到客戶端的請求之後,由服務器端先處理,然後再把結果和相應代碼發回客戶端。

#region ICallbackEventHandler Members
public string RaiseCallbackEvent(string eventArgument)
{
int result;
if (!Int32.TryParse(eventArgument, out result))
throw new Exception("The method is not implemented.");
return "Valid Data";
}
#endregion 最後,在jscript.js文件中寫好相應的回調處理函數即可:
var args;
var ctx;
function ValidateText(ctl)
{
if(ctl.value=='')
{
alert("Please enter a value");
ctl.focus();
}
}
function CallbackHandler(args,ctx)
{
alert("The data is valid");
}
function ErrorHandler(args,ctx)
{
alert("The data is not a number");
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved