用HttpHandler给Asp.net 1.1加入OnClientClick_[Asp.Net教程]                                           					
大家用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);
        }                
        }
    }
    }
}
来源:http://www.cnblogs.com/northdevil