打印本文 打印本文 关闭窗口 关闭窗口
为ASP.NET WEB自定义控件添加提交事件
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1010  更新时间:2009/4/23 10:43:44  文章录入:mintao  责任编辑:mintao

ASP.NET WEB自定义控件添加提交事件

大毛http://damao.0538.org

在Visual Studio.Net提供的服务端控件中有一个叫做“LinkButton”的,它看上去像个链接可是点击时产生像Button一样的Click提交事件。那么我们自己做的自定义控件如何实现这一功能呢?下面的代码讲述这一功能的实现。

1. 首先创建一个Web自定义控件项目命名为Demo,空间源代码文件命名为DemoLinkButton。

2. public class DemoLinkButton : System.Web.UI.WebControls.WebControl,IPostBackEventHandler 控件类继承System.Web.UI.WebControls.WebControl并实现接口IPostBackEventHandler中的方法:RaisePostBackEvent( string )。

3. 修改Text属性。

[Bindable(false),

              Category("Appearance"),

              DefaultValue("")]

         public string Text

         {

              get

              {

                   string _text = (string)ViewState["Text"];

                   return _text == null ? "" : _text;

              }

              set

              {

                   ViewState["Text"] = value;

              }

         }

4. 向页面注册处理提交的Javascript代码。

protected override void OnPreRender(EventArgs e)

         {//产生使页面提交的Javascript函数,这个函数要用到Hyperlink的href中。

              string scriptClick="<script language=''''javascript''''>function DoOnClick(){"+((HyperLinkClicked==null)?"":(Page.GetPostBackClientEvent(this,"Clicked"))+"; return;}</script>");

              Page.RegisterClientScriptBlock("OnClicked",scriptClick);

         }

5. 向页面输出控件显示。

protected override void Render(HtmlTextWriter output)

         {

              if(this.Text == "")

              {

                   output.Write("<a href=\"javascript:DoOnClick();\" id=\"" +this.ClientID+ "\">DemoLinkButton</a>");

              }

              else

              {

                   output.Write("<a href=\"javascript:DoOnClick();\" id=\"" +this.ClientID+ "\">"+this.Text+"</a>");

              }

         }

6. 最后实现IPostBackEventHandler接口。

public void RaisePostBackEvent(string eventArgument)

         {

              if (eventArgument=="Clicked") HyperLinkClicked(this,EventArgs.Empty);

         }

这样一个自定义回发事件的控件就完成了,与类库中的LinkButton基本相似,点击链接产生提交事件,在代码页处理HyperLinkClicked事件就可以了。

 

打印本文 打印本文 关闭窗口 关闭窗口