Call a JavaScript method/code from Asp.Net Code behind

In day to day development, we face a requirement that we need to call a JavaScript method or some lines of JavaScript code from code behind. There are several ways to accomplish this.

  1. Using ScriptManager Class.
  2. Using Page.RegisterClientScriptBlock or Page.RegisterStartupScript or Page.ClientScript object

Page.RegisterClientScriptBlock or Page.RegisterStartupScript methods are deprecated methods and they shouldn’t be used. Microsoft has replaced them with Page.ClientScript object methods.

ScriptManager class can also be used to do the same but with the slight difference, these methods are compatible with Asp.Net AJAX partial post backs where as the Page.ClientScript object methods are not compatible with Asp.Net AJAX.

Also, in ScriptManager class there are various methods to perform this operation.

  1. RegisterClientScriptBlock
    This method is useful when a client script block i.e. some JavaScript method calls or operations are to be done.
  2. RegisterClientScriptInclude
    This method is useful when a JavaScript file needs to be included.
  3. RegisterClientScriptResource
    This method is useful to get the JavaScript file embedded from the assembly.

All these methods have an overload in which one takes Control as first parameter and the other overload takes Page as a first parameter.

Recently, I faced the issue in which I had a requirement to update a JavaScript object on every partial post back. I was using the RegisterClientScriptBlock with the Control as first parameter, it was not being updated.

Here is the catch, if you use Control as the first parameter then the JavaScript would be only registered once and it won’t be updated but if you use Page as the first parameter then the JavaScript would be updated on every partial post back.

Advertisements

One thought on “Call a JavaScript method/code from Asp.Net Code behind

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s