March 14, 2019

How to disable ASP.Net button after click (prevent double clicking)

There could be two possible options you can apply to disable asp.net button after click to keep user from double clicking. Simple disabling the button won't help because you may also have to deal with client side validation on form controls.

For example, we have following markup with asp.net textbox and button.

 <div class="col-md-6">
  <div class="form-group">
   <label>
    User Name: 
    <asp:RequiredFieldValidator runat="server" ControlToValidate="txtUserName" ErrorMessage="Required"
     CssClass="Validator" SetFocusOnError="True" ValidationGroup="SaveUser">*</asp:RequiredFieldValidator>
   </label>
   <asp:TextBox ID="txtUserName" runat="server" class="form-control" ></asp:TextBox>
  </div>
 </div>

 <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CssClass="btn btn-primary" ValidationGroup="SaveUser"/>

We have to disable this asp.net button after clicking. Following options will help you prevent double click problem while also considering client side validation.

  • First option is to use OnClientClick event of asp.net button. We have to return false if client validation failed, else we will disable the button and optionally change the button text to indicate some progress. We also have to set UseSubmitBehavior property value to false. Final markup for the button will be:

       <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CssClass="btn btn-primary" ValidationGroup="SaveUser"
        OnClientClick="if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';" 
        UseSubmitBehavior="false"
       />
      
  • Second option is to disable the button on post back event from JavaScript, i.e. window.onbeforeunload. Here is the button markup and script which sets button's disabled property, optionally you can also change button's text to indicate progress for post back event.

       <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CssClass="btn btn-primary" ValidationGroup="SaveUser"/>
      
      <script type = "text/javascript">
       function disableButton() {
        document.getElementById("<%=btnsave.ClientID %>").disabled = true;
        document.getElementById("<%=btnsave.ClientID %>").value = 'Saving...';
       }
       window.onbeforeunload = disableButton;
      </script>
      

I hope this helps some of you who get stuck with a similar problem.

1 comment:

  1. thanks for posting. This is the best solution that I've found so far. I did option # 1

    ReplyDelete