Saturday, 16 March 2013

Non Ajax solution for disabling a button after click for full .NET postbacks

It's that old chestnut where you want to disable a button after the user clicks it to prevent them potentially clicking it again and accidental calling the server side event twice. This is especially an issue for longer running tasks .

This may sound really easy to do at first , just disable it with javasctip right ? But when you try this, you'll find that with disabling a submit button on the client side will cancel the browser’s submit, and thus the postback. Not what you want to happen!

There are a few methods going around to do this , but i find this one the easiest , kick back to Encosia where i first found this approach.

This method is to use the OnClientClick and UseSubmitBehavior properties of the button control.

<asp:Button runat="server" ID="BtnSubmit"
  
OnClientClick="this.disabled = true; this.value = 'Submit in progress...';"
  
UseSubmitBehavior="false"
  
OnClick="BtnSubmit_Click"
  
Text="Click to Submit" />


OnClientClick allows you to add client side OnClick script. In this case, the JavaScript will disable the button element and change its text value to a progress message. When the postback completes, the newly rendered page will revert the button back its initial state without any additional work

No comments:

Post a Comment