当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET 2.0中控件的简单异步回调

ASP.NET
blog程序新版本V2.0 Beta完成,提供V1.0全部源码下载
“/”应用程序中的服务器错误
asp.net(c#)复数类(复数加减乘除四则运算)
asp.net(c#)不可访问,因为它受保护级别限制
asp.net(c#) 水仙花数
ASP.NET实现用图片进度条显示投票结果
asp.net(c#) MS AJAX的安装
asp.net(c#)有关 Session 操作的几个误区
ASP.net基础知识之常见错误分析
[.net] 操纵自如-页面内的配合与通信
c# static的全部用法收集整理
使CheckBoxList的Attributes属性生效(修改微软的一个bug)
在ASP.NET中使用Session常见问题集锦
[原创]完美解决Could not load file or assembly ''AjaxPro.2'' or one of its dependencies. 拒绝访问。
在Apache环境下成功的运行ASP.NET的注意事项
ClickOnce DIY全自动更新下载升级的自我实现
asp.net jscript 一句话木马
在ASP.Net中实现flv视频转换的代码
将DataTable中的一行复制到另一个DataTable的方法
在DataTable中执行Select("条件")后,返回DataTable的方法

ASP.NET 2.0中控件的简单异步回调


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 104 ::
收藏到网摘: n/a

虽然已经有了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 OnPreRe nder(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"); }