0

When I click in the button, the action goes to the server. It's ok. But when I click in this button 2,3,4 or more times, it goes to the server and records multiple times in the database. There is a correctly way to do it? Thanks!

ASP:

<asp:button id="btn" runat="server" text="Click"></asp:button>

VB:

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles btn.Click
.... my function ...
End Sub

I HAVE FOUND THIS SOLUTION

<script language='javascript' type="text/javascript"> 
    var clicks = 0; 
    function SubmitOnce(btn) { 
        clicks = clicks + 1; 

        if (clicks == 1) return true; else { btn.disabled = 'true'; return false; } 
    } 
</script>

2 Answers2

0

Inside your btn_Click method you can set at the end of execution an btn.Enable=false like @ huMptyduMpty comment

and to make this safer, you can use yet a javascript code like:

function setDisable(el){
el.setAttribute('disabled', 'disabled');
}

and ont the element:

<asp:button id="btn" runat="server" text="Click" onclientclick="setDisable(this);"></asp:button>

haven't tried the code, but I think that you catched the idea ;-)

Edit: Another approach is fi it's not a problem, you can set display:none on the element to prevent a second click, so when the first click's postback ends, the button turn visible again...

and if the user has to click one time and no more, then you can use the tip above and set on the server to this button stay enabled = false and display:none

Luiz Eduardo
  • 380
  • 4
  • 13
  • I got it @servergta. I tried it, but it doesn't work. Because if I do it, the action of the button doesn't go to the server. Not even if I put `return true;`. You can check the same problem here: [http://stackoverflow.com/questions/6137172/how-do-i-prevent-users-clicking-a-button-twice](http://stackoverflow.com/questions/6137172/how-do-i-prevent-users-clicking-a-button-twice) – Guilherme Natal de Mello May 06 '14 at 19:46
0

In your code just use the same logic you tried with javascript, but limit it. Set up a variable that loads and gets set to '0' when the page loads. After the value of the variable changes, no longer allow the action to be carried out.

Dim button_pressed as integer = 0

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles btn.Click

button_pressed +=1

if button_pressed = 1 then
 ' perform your action
else
 ' disallow the action
endif

End Sub
John
  • 1,310
  • 3
  • 32
  • 58