Disable Webform Button After Validation And Before Postback
Solution 1:
You can see in the rendered button HTML your single quotes are getting changed to '
, which is an ASP.NET security feature. Some posts on SO (like Stop the tag builder escaping single quotes ASP.NET MVC 2) have posted away to get around this, but I personally would NOT take that route.
Note, for both of these examples I added a return false
to stop the form submission so you can see the button actually disable. Remove this when you are ready to continue testing your code.
You can either just put your code in the button itself:
<asp:ButtonID="FinalButton"runat="server"OnClientClick="if(Page_ClientValidate('vg')){this.disabled = true; return false; }"Text="Final Submit"ValidationGroup="vg" />
This works, but looks nasty. It's cleaner to not have that OnClientClick
just add the click event with Javascript:
<script>
$("#<%= FinalButton.ClientID %>").click(function () {
if (Page_ClientValidate('vg')) {
this.disabled = true; returnfalse;
}
});
</script>
Ok so once you see that working, and you remove the return false;
, you are still going to have issues. Namely that a disabled button doesn't perform a postback in certain browsers. So some browsers will postback, others will act just like it did with the return false;
. That's not good.
What is worse is regardless of the browser, ASP.NET is not going to run the click event of a disabled button (if you add something like OnClick="FinalButton_Click"
to the button). You can test this out in IE9, since a disabled button will still post back, but you can see your OnClick
event won't fire. Chrome on the other hand will just disable your button and not postback.
Solution 2:
You can use the setTimeout trick to disable the button right after the postback is triggered:
<script>
$("#<%= FinalButton.ClientID %>").click(function ()
{
var self = this;
setTimeout(function ()
{
self.disabled = true;
}, 0);
});
</script>
Solution 3:
After searching for hours I found out that you can use UseSubmitBehavior="false"
to allow asp postback to handle the button instead of the normal browser submit. You can read the docs here
This also means your OnClientClick
script does not have to return true
<asp:ButtonID="btnSave"runat="server"Text="Save"OnClientClick="this.disabled=true"OnClick="btnSave_Click"UseSubmitBehavior="false"/>
Post a Comment for "Disable Webform Button After Validation And Before Postback"