Thursday, May 10, 2018

ASP .NET AJAX - Maintain Or Set Page Scroll Position After Asynchronous Postback In ASP.NET AJAX



Now just add the below JavaScript code to the relevant section of your Web Page.


  1. <script type="text/javascript">  
  2.     var xPos, yPos, needScroll;  
  3.     var prm = Sys.WebForms.PageRequestManager.getInstance();  
  4.     prm.add_beginRequest(BeginRequestHandler);  
  5.     prm.add_pageLoaded(EndRequestHandler)  
  6.   
  7.     function BeginRequestHandler(sender, args) {  
  8.         xPos = 0;  
  9.         yPos = window.pageYOffset || document.documentElement.scrollTop;  
  10.     }  
  11.   
  12.     function EndRequestHandler(sender, args) {  
  13.         if (needScroll) {  
  14.             window.setTimeout("window.scrollTo(" + xPos + "," + yPos + ")", 100);  
  15.         }  
  16.     }  
  17. </script>  


After adding the above code at page script Tag on your code behind you need to add the below code at your .cs page to call the Javascript function after page completes its rendering after postback.


ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "ScrollTo", "var needScroll = true;", true);

No comments: