Prevent user from clicking twice at a button with ASP.NET AJAX

Home Articles Downloads Links About


The following article shows how it can be used ASP.NET AJAX to prevent the user to click accidently again at a button while the previous asynchronous request is still processing.


With ASP.NET AJAX you can make an asynchronous postback on a page. But on the server-side there could be required some long processing operations to handle the requests. In this case, it could be essential to prevent the user from accidently initialing another request. The Microsoft AJAX script library provides the PageRequestManager class that could be useful in these situations.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">

<head runat="server">

    <title>Untitled Page</title>    



    <form id="mainForm" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

    <script type="text/javascript" language="javascript">

        var lastPostBackId = '';

        var pageReqMan = Sys.WebForms.PageRequestManager.getInstance();



        function checkSubmitButton(sender, args)


            if (pageReqMan.get_isInAsyncPostBack() && args.get_postBackElement().id==lastPostBackId)






                lastPostBackId = args.get_postBackElement().id;




    <asp:UpdatePanel ID="mainUpdatePanel" runat="server" UpdateMode="Conditional">



                <asp:Label ID="resultLabel" runat="server" Text=""></asp:Label>

                <asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />







The above example uses:

1.       ScriptManager (ScriptManager1), UpdatePanel (mainUpdatePanel) and a button (submitButton) to create an AJAX request that take long time to be processed.

2.       To handle the situations then the user click again the button before the previous request is processed, in client-side it’s created an instance of the PageRequestManager.

3.       For the initializeRequest event of the PageRequestManager class it created a handler (checkSubmitButton)

In this handler it is checked if the asynchronous request is still executing and if it’s initiated by the same element. If this is the case the request is canceled. Else it’s stored the id of the element that caused the postback.