阅读文章

用HttpHandler给Asp.net 1.1加入OnClientClick

[日期:2008-04-08] 来源:  作者: [字体: ]

     大家用ASP.net 1.1的时候,对ASP:button加入客户端的onclick事件,要在code-behind里利用Button的Attributes集合,加入,例如:
  this.Button1.Attributes["onclick"] = "return test();";
  
  说来惭愧,没出ASP.net 2.0的时候,虽然觉得这么做有点麻烦,但也没想着要去改进它,直到ASP.net 2.0出现,看到了在2.0里,多了OnClientClick这个属性,简化了上面1.1时的做法。
  
  其实,在1.1下面,可以用HttpHandler来达到简化onclick的功能。在这个Handler里,遍历页面的每个控件,发现它存在OnClientClick的Attribute时,就给控件加一个onclick的Attribute,然后在web.config里配置所有的ASPx页面用这个HttpHandler处理,这样就达到了我们简化onclick的目的,使ASP.net 1.1也支持OnClientClick。
  
  
  using System.Collections;
  using System.Web;
  using System.Web.Compilation;
  using System.Web.SessionState;
  using System.Web.UI;
  namespace ZSoft.Web.Controller
  {
  
   class ASPNet1ExtendHandler : IHttpHandler, IRequiresSessionState
   {
   IHttpHandler 成员#region IHttpHandler 成员
  
   public bool IsReusable
   {
   get { return false; }
   }
  
   public void ProcessRequest(HttpContext context)
   {
   string url = context.Request.Path;
   IHttpHandler h = PageParser.GetCompiledPageInstance(url,context.Server.MapPath(url),context);
   (h as Page).PreRender += new EventHandler(ctx_PreRender);
  
   context.Handler = h;
   // 交由ASP.net默认的Handler处理
   h.ProcessRequest(context);
   }
  
   #endregion
  
  
   private void ctx_PreRender(object sender, EventArgs e)
   {
   Extend(sender as Page);
   }
  
   private void Extend(System.Web.UI.Control control)
   {
   string script = GetAttribute(control,"OnClientClick");
   if(script != null)
   {
   AddAttribute(control,"onclick",script);
   }
   foreach(Control child in control.Controls)
   {
   Extend(child);
   }
   }
   private string GetAttribute(Control control,string keyword)
   {
   if(control is WebControl)
   {
   return (control as WebControl).Attributes[keyword];
   }
   if (control is HTMLControl)
   {
   return (control as HTMLControl).Attributes[keyword];
   }
   }
  
   private void AddAttribute(Control control, string key, string value)
   {
   string oldValue = GetAttribute(control, key);
  
   if (oldValue != null)
   {
   if (oldValue.IndexOf(value) != -1) oldValue = oldValue.Remove(oldValue.IndexOf(value), value.Length);
   if (!oldValue.EndsWith(";") && oldValue != "") oldValue += ";";
   }
   value = oldValue + value;
   if (control != null)
   {
   if (control is WebControl)
   {
   WebControl webCtrl = control as WebControl;
   webCtrl.Attributes.Add(key, value);
   }
   if (control is HTMLControl)
   {
   HTMLControl HTMLCtrl = control as HTMLControl;
   HTMLCtrl.Attributes.Add(key, value);
   }
   }
   }
  
   }
  }
    


阅读:
录入:blue1000

评论 】 【 推荐 】 【 打印
上一篇:在.Net中使用异步(二)
下一篇:wf框架编程(监控部分)
相关文章      
本文评论
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款