Sunday, July 29, 2012

How can I protect by asp.net button from click multiple time or double click at a time?

Problem:  How can I protect by asp.net button from click multiple time or double click at a time?

Solution:
When clicking in save or insert button a user can click multiple times very quickly that sometimes is similar to double click. If you do not protect users from double click while inserting data, it may insert multiple records at a time which is unexpected.  Asp.net developers frequently face the problem.

To protect from this problem you need to add small java script function.

If you are not using validation group in your page then the function will be:


        <script language="javascript" type="text/javascript">
        var crnt = 0;
        function PreventClicks() {

            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>



<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" OnClick="InsertNewUser" Text="Save" OnClientClick="return PreventClicks();" />


If you use validation group then the function will be:


    <script language="javascript" type="text/javascript">
        var crnt = 0;
        function  PreventClicks() {

            if (typeof (Page_ClientValidate('change-password')) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>


<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" 

ValidationGroup="change-password"

OnClick="InsertNewUser" Text="Save" dd OnClientClick="return PreventClicks();" />


Hope that it will be helpful for developers.

4 comments:

  1. if you click only one time click event is fired in that button.
    if you click double click,double click event is fired.

    ReplyDelete
  2. I liked seeing this, needed some more images though.

    ReplyDelete
  3. There are two different event provided by asp.net to handle some event using single or double click event.

    ReplyDelete
  4. Thanks sir..

    Please Keep it up.. :)

    ReplyDelete