RegisterClientScriptBlock, RegisterStartupScript and the AJAX Update Panel

It’s very frustrating when Microsoft products don’t work with Microsoft products and the server side client script is one of those frustrating situations.

Normally, if I need to fire off a client script server side I would do it like this:

  1. An asp:Button called myButton has been clicked on the page
  2. The following event is fired:
    Private Sub myButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles myButton.Click
         'Do some server side processing
    
         Dim script as String = ""
         script = "<script language='javascript' id='myScript'>"
         script += "alert('some alert text');"
         script += "</script" + ">"
    
         If Not ClientScript.IsClientScriptBlockRegistered("myScript") then ClientScript.RegisterClientScriptBlock(System.Type.GetType("System.String"), "myScript", script)
    End Sub
  3. If you’re building you’re application in DotNetNuke replace that last line calling the ClientScript with this line:
    If Not Page.ClientScript.IsClientScriptBlockRegistered("myScript") Then Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), script)

But, if myButton is included as a trigger on an Update Panel then the ClientScript won’t fire.  The Update Panel itself is firing client side code which will keep ClientScript from being added to the view state and firing.

Instead, use ScriptManager:

Private Sub myButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles myButton.Click
     'Do some server side processing

     Dim script as String = ""
     script = "<script language='javascript' id='myScript'>"
     script += "alert('some alert text');"
     script += "</script" + ">"

     ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), script, True)
End Sub

For more detailed info: Differences between RegisterClientScriptBlock & RegisterStartupScript and how they work with AJAX Update Panel

Leave a Reply

Your email address will not be published. Required fields are marked *