Wednesday 2 April 2014

Submit button allowed to click only once with an ASP.NET Button Server Control

Introduction

It is often a required functionality that a button is only allowed to be clicked once during data submission in a web application. Clicking the button more than once might cause irrecoverable damage.

One of the solution i found useful in our case is:

  • Properly set up the properties of the button server control to enable client side click event and to change its submission behavior

Set Up Button Server Control Properties

Two of the properties of an ASP.NET button server control are of our interest:

  • UseSubmitBehavior: False
  • OnClientClick: this.disabled = true;

When UseSubmitBehavior is set to False, the button server control is rendered to a client browser as an HTML “button” (HTML <input> tag with type=“button”) instead of an HTML “submit button” (HTML <input> tag withtype=”submit”) which is the default behavior. As a result, client side JavaScript is able to intercept the submission process when the button is clicked.

The OnClientClick property specifies a client side JavaScript function. When the button is clicked, this function is executed first before submitting data to server. A decision can be made at client side for whether or not the submission should continue based on the result of client side validation.

If you disable a button in onclientclick, other events will not fire because the object they are tied to is disabled. So we need to set UseSubmitBehavior  to false so that javascript will take care of submitting the button.

HTML code of an ASP.NET button server control with the UseSubmitBehavior and OnClientclick properties at design time is shown below:

<asp:Button ID="btnSubmit" runat="server" CssClass="btn-active"   
Text="Submit Data" onclientclick="this.disabled = true;"   UseSubmitBehavior="False"
onclick="btnSubmit_Click" />

After being rendered to a client browser, the HTML code will look like that shown below. Note that the type is “button” but not “submit”. The event handler WebForm_DoPostBackWithOptions(...) deals with server side click while the onclick="this.disabled = true;" is for client side click.

<input type="button" name="btnSubmit" value="Submit Data" onclick="this.disabled = true;
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnSubmit&quot;,
&quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))" id="btnSubmit"
class="btn-active" style="width:120px;" />

With the above two properties properly set, the button can be disabled at client side during submission to prevent it from being clicked more than once. In addition, a warning message may also be displayed or the current page may be completely greyed out to indicate the progress of data processing at server side.