How to Disable Buttons during AJAX Postback in ASP.NetHow to easily disable buttons during AJAX postbacks or other operations so that you don't end up doing multiple requests.
It is an often overlooked requirement to disable controls on postback during an AJAX postback event to prevent repetitive clicking, a minor problem which can become more serious depending on the action being taken. Payment processing, for example, can result in multiple payments or orders if not handled correctly.
I'll start with a very basic AJAX form - a single button and an UpdateProgress control and from here we'll look at how to disable buttons during AJAX Postback. This also works for any other control that you wish to update during a postback request.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="updPanel1" runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="btnSubmit_Click"/>
<asp:UpdateProgress runat="server" ID="ajaxProgress">
<ProgressTemplate>Please wait...</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have bound the OnClick event to the btnSubmit_Click which will create a delay of 5 seconds.
protected void btnSubmit_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
}
If you create a new AJAX-enabled website, copy the above code and run the site you will notice that when you click the button the progress is shown and you can click the button as many times as you want. Depending on your situation this can cause many undesirable effects such as multiple record creation, duplicate payment processing and higher server loads.
This can all be combated using the following Javascript. The only thing you need to do is change the name of the button to whatever you are calling it. You can also add the name of any other control on the form - text boxes, drop-down lists and so on. These will also be disabled while the postback is in progress. Remember to modify both the instances where btnSubmit exists otherwise, you may find that your controls do not get enabled again.
(function() {
Sys.Application.add_load(setupButtonDisablers);
function setupButtonDisablers() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(onPageLoad);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(onSubmit);
Sys.Application.remove_load(setupButtonDisablers);
}
function onPageLoad() {
findAndEnable('<%= btnSubmit.ClientID %>'); / Change this
}
function onSubmit() {
findAndDisable('<%= btnSubmit.ClientID %>'); / Change this
}
function findAndDisable(id) {
findAndSetDisabledProperty(id, true);
}
function findAndEnable(id) {
findAndSetDisabledProperty(id, false);
}
function findAndSetDisabledProperty(id, value) {
var control = $get(id);
if (control) {
control.disabled = value;
}
}
})();