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 returnfalse
if client validation failed, else we will disable the button and optionally change the button text to indicate some progress. We also have to setUseSubmitBehavior
property value tofalse
. 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'sdisabled
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.