All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
用HttpHandler给Asp.net,1.1加入OnClientClick_[Asp.Net教程]

Writer: 归海一刀 Article type: Programming skills(编程技巧) Time: 2014/1/30 1:12:36 Browse times: 344 Comment times: 0

用HttpHandler给Asp.net,1.1加入OnClientClick_[Asp.Net教程]


Head photo

Go homepage
Upload pictures
Write articles

用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





There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.