CODEDIGEST InstallShield
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » CodeDigest » Using RegisterClientScriptBlock() Methods of ClientScriptManager Class   You are not logged in.
Search
 

Sponsors
InstallShield
 

Sponsored Links
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using RegisterClientScriptBlock() Methods of ClientScriptManager Class
Using RegisterClientScriptBlock() Methods of ClientScriptManager Class
Submitted By Satheesh Babu
On 4/22/2009 7:17:49 AM
Tags: ASP.Net 2.0,CodeDigest  

Using RegisterClientScriptBlock() Methods of ClientScriptManager Class

 

From ASP.Net 2.0, Page.RegisterStartUpScript() and the Page.RegisterClientScriptBlock() methods are considered obsolete. Currently, these two methods are now packed with ClientScriptManager class. The RegisterClientScriptBlock() method allows you to place a JavaScript function at the top of the page and it gets executed on startup of the page (when loading the page in the browser). There is an additional method called IsClientScriptBlockRegistered() in ClientScriptManager which will return true if a script block is already registered with the same key, hence, we can prevent the duplicate script registration.

 

There are 2 overloads for this method.

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key,

String script)

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key,

String script, Boolean addScriptTags)

 

Implementation

Placing this code on page load or a button click makes the script to fire on the start up of subsequent postback.

 

1st overload implementation

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))

{

script.RegisterClientScriptBlock(this.GetType(), "Alert",

"<script type=text/javascript>alert('Welcome to CodeDigest.Com')</script>");

}

 

2nd overload implementation

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))

{

script.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('Welcome to CodeDigest.Com')",true);

}

 

As I said earlier, these methods will make the script block to execute on the startup, thus we can see the alert box before the actual controls are rendered or before the controls are visible on the page.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!