Daily Archives: 05/22/2012

Regenerate JavaScript function code in ASP.NET partial postback after initial load

ASP.NET has a handy way of generating client side JavaScript code, but using it can be sometimes unpredictable. For example your client-side script needs to call function MyAlert, but the function itself is generated server-side on page load:

ClientScript.RegisterStartupScript(Me.GetType, "JSCode", _
                  "function MyAlert() {alert('This is the FIRST call')}", True)

Function is generated, and in due time, when needed is called by the client and the message “This is the FIRST call” is displayed. All is well.

Now, your page also has an UpdatePanel, and during a partial postback you need to modify that client-side function:

ScriptManager.RegisterStartupScript(Me, Me.GetType, "JSCode", _
                  "function MyAlert() {alert('This is the SECOND call')}", True)

In due time, when again needed by client code, function MyAlert is called and the message (wait for it, you’re in for a surprise) “This is the FIRST call” is displayed again. Originally generated function is called and second generation is ignored. Continue reading →