DavidSpot Blog

Developer, super curious, a dog lover, sports fan and techie guy


ASP.NET WebForms - Register javascript method or code in PostBack and Partial Postback from Update Panel

Back in the day when I was starting to develop some enterprise web apps with ASP.NET WebForms I found it really easy to move from Desktop apps that I was used to do in Java while I was at the University because Microsoft did a really great work on abstracting the http stateless nature with the framework. 

 
Basically all you had to do was drag-and-drop some controls and voilá, you have yourself a pretty WebApp almost with no effort, of course this "mimic" migration from Desktop-to-Web had is price... the well know full postback cycle of rendering all the page. 
 
This is when I got to know javascript (to make "things" faster in the client) and the concept of partial update with ajax (yes, AJAX it's a well know cleaning product in Portugal and a one of the biggest football Dutch teams).
 
Anyway any how, I was having some problems when I needed to run any javascript, at the end of a postback or in a partial postback.
 
So I came across to useful methods, ScriptManager.RegisterStartUpScript and ClientScriptManager.RegisterClientScriptBlock and they work like this:
 
  • If you want to run javascript in the end of a postback you should use the ClientScriptManager.RegisterClientScriptBlock like this:
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
 
  • If you want to run javascript in the end of a partial-postback (this is the same to say an update from an UpdatePanel) you should use the ScriptManager.RegisterStartupScript like this:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),"SomestartupScript","alert('page loaded');", True)