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

Home Articles Downloads Links About

Summary

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.

Introduction

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.

Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>    

</head>

<body>

    <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();

        pageReqMan.add_initializeRequest(checkSubmitButton);

   

        function checkSubmitButton(sender, args)

        {

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

            {

                args.set_cancel(true);

            }

            else

            {

                lastPostBackId = args.get_postBackElement().id;

            }

        }

    </script>

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

        <ContentTemplate>

            <div>

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

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

            </div>

        </ContentTemplate>

    </asp:UpdatePanel>

    </form>

</body>

</html>

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.