• Home
  • About
  • Resume

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

By , 05/22/2012 3:20 PM

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.

To rectify the situation you need to declare function as a variable (empty initially) in your client code:

var MyAlert;

And then modify server-side generation code to use assignment notation (instead of function MyAlert use MyAlert = function):

Initial load:

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

and partial postback

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

after these changes client-side code behaves as expected and freshly generated function is called every time.

Leave a Reply

Panorama Theme by Themocracy