September 2nd, 2009Disabling a Submit Button in an AJAX Update Panel to Prevent Double Posting
This is one of those ideas I wish I was smart enough to come up with myself. But my hat is off to Alex Arkhipov who came up with a nifty solution to prevent the dreaded double-postback.
You might remember that this issue has been a common theme for me.
It seems that no matter how quick and well designed my UI is, users still find ways to insert multiple records into my database by double-clicking. It never used to be an issue when the entire page would post back, however, with the latest AJAX tools and functionality, it happens more and more.
In any event, Alex came up with this simple solution that appears to be working great!
Essentially, he adds client-side page event handlers that disable the calling button during an initializeRequest event and re-enables it during an endRequest event. Simply brilliant!
I modified the code a bit to remove the styling from CSS. I just needed the button to be disabled.
Then, I placed this code inside of my master page so all of my child pages could take advantage of this functionality.
<script type="text/javascript">
function pageLoad(sender, args) {
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(initializeRequest);
rm.add_endRequest(endRequest);
}
function initializeRequest(sender, args) {
//Disable button to prevent double submit
var btn = $get(args._postBackElement.id);
if (btn) {
btn.disabled = true;
}
}
function endRequest(sender, args) {
//Re-enable button
var btn = $get(sender._postBackSettings.sourceElement.id);
if (btn) {
btn.disabled = false;
}
}
</script>