How To Allow Only One Button Click In Long Time Operations?
If you need to execute long time operation, there is a possibility that visitor could think that something is wrong with your web application and will try to click button again and start operation again. In that case, you need to allow only one click to button and disable other clicks until long operation is completed. There are a few different ways to achieve this, I use this one:
[ C# ]
public
partial class
_Default : System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
// Client side code will change button text to
// Please wait... and disable future clicks
btnOnlyOnce.OnClientClick = @"if(this.value ==
'Please wait...')
return false;
this.value = 'Please wait...';";
}
protected void
btnOnlyOnce_Click(object sender,
EventArgs e)
{
// Code execution will wait for a 5 seconds
// so you can try to click a button more than once
System.Threading.Thread.Sleep(5000);
btnOnlyOnce.Text = "Long operation is finished";
}
}
[ VB.NET ]
Partial
Class _Default
Inherits System.Web.UI.Page
Protected Sub
Page_Load(ByVal sender
As Object, ByVal
e As System.EventArgs)
Handles Me.Load
' Client side code will change button text to
' Please wait... and disable future clicks
btnOnlyOnce.OnClientClick = "if(this.value ==
'Please wait...')" & _
"return false; " & _
"this.value = 'Please wait...';"
End Sub
Protected Sub
btnOnlyOnce_Click(ByVal sender
As Object,
ByVal e As
System.EventArgs) Handles btnOnlyOnce.Click
' Code execution will wait for a 5 seconds
' so you can try to click a button more than once
System.Threading.Thread.Sleep(5000)
btnOnlyOnce.Text = "Long operation is finished"
End Sub
End
Class
I like this way because it is pretty efficient, but it is a little bit hard coded. If you know a better way please let me know.
Related articles:
1. ASP.NET Configuration System