Page.RegisterStartUpScript() and the
Page.RegisterClientScriptBlock() methods in .NET Framework 1.x are now
considered obsolete. These two methods are now packed with ClientScriptManaget
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.
Listing 1 - RegisterClientScriptBlock Overloads
ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key,
String script)
ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key,
String script, Boolean addScriptTags)
Usage
Placing this code on page load or a button click makes the
script to fire on the start up of subsequent postback.
Listing 2 - 1st overload
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
{
script.RegisterClientScriptBlock(this.GetType(), "Alert",
"<script type=text/javascript>alert('hi')</script>");
}
Listing 3 - 2nd overload
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
{
script.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('hi')",true);
}
Figure 1 - RegisterClientScriptBlock Output
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 controls
are actually rendered.