• Home
  • About
  • Resume

Run JavaScript from both full and partial ASP.NET postback

By , 03/03/2011 4:23 PM

A while back I posted a function that would run JavaScript from both full page postback and Infragistics async postback. But what if you’re using “normal” Microsoft AJAX where partial postbacks are controlled by ScriptManager and you need to run JavaScript on initial page load, full postback and from inside of Update Panel? And even in Infragistics the newer Aikido controls use ScriptManager for async communications.

Here is an overridden version of that RunJavaScript function for pages with ScriptManager:

Public Shared Sub RunJavascript(ByVal _
   i_oScriptManager As Web.UI.ScriptManager,  ByVal i_sJScode As String)

   If i_oScriptManager.IsInAsyncPostBack Then
      i_oScriptManager.RegisterStartupScript(i_oScriptManager.Page, _
      i_oScriptManager.Page.GetType, "JSCode" & Rnd(1).ToString, _
      i_sJScode, True)
   Else
      i_oScriptManager.Page.ClientScript.RegisterStartupScript( _
      i_oScriptManager.Page.GetType, "JSCode" & Rnd(1).ToString,
      i_sJScode, True)
   End If
End Sub

It accepts 2 parameters – ScriptManager control from the page and string with JavaScript code. Function checks if it’s an async postback and if so – calls ScriptManager’s RegisterStartupScript method, otherwise page’s RegisterStartupScript is used. Here’s an example of usage:

RunJavascript(Me.ScriptManager1, "alert('Hello world from any postback!');")

Leave a Reply

Panorama Theme by Themocracy