A day with .Net

My day to day experince in .net

Disable button on ajax post back.

Posted by vivekcek on March 8, 2012

Some times ajax post back can take time.Its a good practice not to allow user to click the button again before the post back is completed.This can be achieved by adding some code in HTML.

In this example my page contain a Script Manger,an update panel and a button inside it .In the buttons click event i simulated a long running process by calling a thread sleep.


protected void Button1_Click(object sender, EventArgs e)
 {
 System.Threading.Thread.Sleep(5000);
 }

Then added a script in HTML.That is fired when an ajax request is made.


<script type="text/javascript">
var page;
function pageLoad() {
page = Sys.WebForms.PageRequestManager.getInstance();
page.add_beginRequest(OnBeginRequest);
page.add_endRequest(OnEndRequest);
}
function OnBeginRequest(sender, args) {
$get(args._postBackElement.id).disabled = true;
}
function OnEndRequest(sender, args) {
$get(sender._postBackSettings.sourceElement.id).diabled = false;
}
</script>

OnBeginReques function find the control that caused the post back(button in our case) and disable that.OnEndRequest is fired after the post back is over and button is re enabled

Download code

https://skydrive.live.com/redir.aspx?cid=12c9d813342f227a&resid=12C9D813342F227A!125&parid=12C9D813342F227A!120&authkey=!ABW5jJ6aLndfff8

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s