Tuesday, December 20, 2011

Disable a button during postback

You may want to disable a button during postback to stop user from clicking the button before the results are returned. You could do this on the client side using the OnClientClick attribute. The problem with disabling a submit button on the client side is that it will cancel the browser's submit, and thus the postback. Hence your server side event (BtnSumbit_Click) will not trigger.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

The trick is to set the UseSubmitBehavior property to false. This tells .Net to inject the necessary client script to fire the postback anyway, instead of relying on the browser's form submission behavior.

asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!"

This property will inject __doPostBack giving us this rendered HTML:

input type="button" name="BtnSubmit"
onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"

No comments: