Wednesday, May 14, 2014

Handle Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript

Here is a simple code to handle all the Synchronous and Asynchronous Postbacks from the ASP.NET Updatepanel using Javascript. We can get the control that makes the Postback. So Its very useful to show/hide loading image when asynchronous Postback happens. JavaScript Code:
<script type="text/javascript">
        $(document).ready(function ()
        {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_initializeRequest(prm_InitializeRequest);
            prm.add_endRequest(prm_EndRequest);
            var ctrl;
            function prm_InitializeRequest(sender, args)
            {
                ctrl = args.get_postBackElement().id;
                if (ctrl == "ContentPlaceHolder1_btnAddUser") 
                {
                $('#imgLoading').show();
                }
            }
            function prm_EndRequest(sender, args)
            {
              $('#imgLoading').hide();
            }
        });
</script>

Note: I have used jquery show/hide function to show/hide loading image. so you have to use the Jquery API.