Saturday, August 31, 2013

Disable a button control during postback


Button disable technique for full .NET postbacks. So, this example is for all of you searching for a non-AJAX solution.
The trick is to use the OnClientClick and UseSubmitBehavior properties of the button control. There are other methods, involving code on the server side to add attributes, but I think the simplicity of doing it this way is much more attractive:
<asp:Button runat="server" ID="BtnSubmit" 
  OnClientClick="this.disabled = true; this.value = 'Submitting...';" 
  UseSubmitBehavior="false" 
  OnClick="BtnSubmit_Click" 
  Text="Submit Me!" />
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.
The one pitfall that comes with disabling a submit button on the client side is that it will cancel the browser’s submit, and thus the postback. Setting the UseSubmitBehavior property to false tells .NET to inject the necessary client script to fire the postback anyway, instead of relying on the browser’s form submission behavior. In this case, the code it injects would be:
__doPostBack('BtnSubmit','')
This is added to the end of our OnClientClick code, giving us this rendered HTML:
<input type="button" name="BtnSubmit" 
  onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"
  value="Submit Me!" id="BtnSubmit" />
This gives a nice button disable effect and processing text, while the postback completes.

The above code does not work on the IE8 browse. So; here we have to implement Disable a button control during postback some different way.

Here we are adding one dummy button on the page in div and make that div display style none. onclick on the btnsubmit we are calling one click side method which disable the btnsubmit and dummy button call the server side event of our original submit button. Below is code for that.

JavaScript Code:

<script> function disableButton() { $("BtnOk").disabled(); $("BtnDummyOk").disabled(); } </script>

HTML Code:


  <p>
        <asp:Button ID="BtnOk" runat="server" Text="Ok"  OnClientClick="disableButton();" />
    </p>

    <div style="display: none;">
        <asp:Button ID="BtnDummyOk" runat="server" Text="Ok"  OnClick="BtnOk_Click"/>
    </div>

It will solve our purpose of disable button and call server side event of the button. Happy Coding !!!! :)





No comments:

Post a Comment