Tuesday, August 25, 2009

Disable asynchronous postbacks while one asynchronous postback is active.

Asynchronous postbacks are partial postbacks occured by Ajax (or any other 3rd party) update panels. Ajax has 5 stages to handle the life cycle of an asynchronous postback. They are:

1. initializeRequest
2. beginRequest
3. pageLoading
4. pageLoaded
5. endRequest

For our work, we need to handle the initializeRequest only. First make sure that your page contains ScriptManager, UpdatePanel, and UpdateProgress controls.

Now, if you want to keep the existing async postback alive, and kill all new async postbacks that are occuring, then add this script:

<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);

function
InitializeRequest(sender, args) {
if (prm.get_isInAsyncPostBack()) {
args.set_cancel(true);
}
}
</script>

if you want to kill the existing async postback and start the new one, then replace the above function with this one:

function InitializeRequest(sender, args) {
if(prm.get_isInAsyncPostBack(){
prm.abortPostBack();
}
}