Practical Javascript 7: PageRequestManager's Begin and End Events

Scripts handlers has worked for me so far because they define in the page processing life cycle those previously obscure phases where (we wished in the past) we could perhaps execute some client-side scripts. These are the PageRequestManager Events. The MSDN documentation defines all the events but I’d like to give an example how I used begin and end event handlers.

The required elements for enabling this event would be to ajaxify the page a web page using a ScriptManager and an UpdatePanel. The panel would contain the button that would trigger the event.

Coding the scripts would be simply putting this script below the ScriptManager tag.

<script type ="text/javascript">

function requestEndHandler(sender, args)
{

    //client-side script that execute after the asynchronous postback

}

function requestBeginHandler(sender, args)

{

    //client-side script that execute before the asynchronous postback

}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(requestEndHandler);

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(requestBeginHandler);

</script>

A common usage for this I do is to disable all submit buttons (in one loop run of the form elements) on a page while the asynchronous postback is happening.

function requestBeginHandler(sender, args)

{

    //client-side script that execute before the asynchronous postback

    affectButtons(true, null);

}

function affectButtons(_isDisabled, _exemptedButtons) {

    var THE_FORM = document.getElementById('aspnetForm');

    for (var x = 0; x < THE_FORM.elements.length; x++)

    {

        if (THE_FORM.elements[x].type == 'submit') {

            if (_exemptedButtons != null) {

                for (var j = 0; j < _exemptedButtons.length; j++) {

                    if (THE_FORM.elements[x].id != _exemptedButtons[j].ToString()) {

                        document.getElementById(THE_FORM.elements[x].id).disabled
                         = _isDisabled;

                    }

                }

            }

            else {

                //no exemptions, disable all buttons

                document.getElementById(THE_FORM.elements[x].id).disabled
                    = _isDisabled;

            }

        }

 

    }//end of for loop

}

Once the script enters requestEndHandler, the buttons are automatically enabled.

Published 07-20-2009 5:25 PM by avcajipe
Filed under: , ,