Monday, June 25, 2007

Creating a Simple ASP.NET "Click Once" Submit Button

I often run into a situation where a user tries to click a Submit button more than once on a page when processing takes more than a few seconds. To remedy this, I created a very simple control based on the standard ASP.NET Button control (System.Web.UI.WebControls.Button). I created a new WebControl and inherit from System.Web.UI.WebControls.Button to retain all of the aspects of a standard button. Next, I override the AddAttributesToRender method and include the following code:

protected override void AddAttributesToRender(HtmlTextWriter writer)
writer.AddAttribute("onclick", "this.disabled=true;"

+ this.Page.ClientScript.GetPostBackEventReference(this, ""));

The first line calls the base classes implementation and then the second line adds a client-side event handler for the "onclick" event of the button. When the button is clicked, it is disabled and then a postback is initiated. This is important because if you just try to disabled the button, it will not be part of the postback and its server-side processing will not fire. That's why you need to include the postback callback function for the button that can be obtained from the call to ClientScript.GetPostBackEventReference.