Click here to Skip to main content
11,581,130 members (64,329 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Downloads
Add your own
alternative version

An improvement to RegisterClientScriptBlock

, 8 Jan 2004 CPOL 243.2K 2.2K 107
A simpler and more flexible method of registering client-side Javascript within ASP.NET pages and controls.
ScriptRegister_src.zip
ScriptRegister
bin
ScriptRegister.dll
scriptregister
scriptregister.GIF
_vti_cnf
scriptregister.GIF
ScriptRegister.csproj.webinfo
<h2><img border="0" src="scriptregister/scriptregister.GIF" width="431" height="241"></h2>
<h2>Introduction</h2>
<p>One of the things that drove me nuts while writing web applications was the 
battle to modularise your code while still keeping generated HTML neat. In 
particular, having individual code modules within a page render their own 
javascript often resulted in pages containing many different and unrelated 
pieces of script scattered in no particular order. It's nice to have javascript 
appear within the <code>HEAD</code> tags of a page, where appropriate, but ASP 
3.0 didn't provide a solution.</p>
<p>ASP.NET does provide a solution, of sorts, in the form of <code>
RegisterClientScriptBlock</code> method in the <code>Page</code> class. This 
allows you to register blocks of client-side script that will, at page render 
time, be output in one neat chunk to the page. I say it's a solution &quot;of sorts&quot; 
because while it's a neat idea, it doesn't actually do what you would always 
hope. </p>
<p>The issues, at least for me, of the <code>RegisterClientScriptBlock</code> 
method were that the script is output after the opening <code>Form</code> tag of 
an ASP.NET page. What if you don't have such a tag in your page? What if you 
want the script output in the HEAD section instead? The method also required you 
to include the &lt;script&gt; tags. To me just meant lots of repeated boiler plate 
code and potential for mistakes. I wanted something that would make it easy to 
include script from many different points within the page creation logic and 
from within controls contained by a page. I also wanted a method that would fill 
in the boiler plate code for me whereever possible.</p>
<h2>A new base class for your webpages.</h2>
<p>With ASP.NET allowing the ability to derive your pages from whatever <code>
System.Web.UI.Page </code>derived class you wish, there will no doubt be a 
plethora of web page base classes available. I could have chosen to encapsulate 
the functionality I needed in a separate utility class which would then be 
instantiated and called from your own <code>System.Web.UI.Page</code> derived 
class, but I'm lazy and so that particular exercise has been left to the reader.</p>
<p>I instead created a simple class, <code>BasePage</code>, derived from <code>
System.Web.UI.Page</code> from subsequent pages can be derived. The methods 
available are:</p>
<h4>RegisterClientScriptBlock</h4>
<p>Registers a client side javascript block. The block is automatically 
surrounded by &lt;script&gt; tags</p>
<pre>void RegisterClientScriptBlock(string key, string script)
void RegisterClientScriptBlock(string key, string script, string language)
void RegisterClientScriptBlock(string key, string script, string language, bool defer)</pre>
<h4>Parameters</h4>
<blockquote>
	<p>key - Script key. If a script file is already registered using this key 
	then the previous script is replaced<br>
	script - The javascript to include.<br>
	Language - The script's language. Default is &quot;Javascript&quot;<br>
	defer - Whether or not the script should be run after the page has fully 
	loaded. Default is false</p>
</blockquote>
<h4>RegisterClientScriptFile</h4>
<p>Registers a client side javascript file include</p>
<pre>void RegisterClientScriptFile(string key, string file)
void RegisterClientScriptFile(string key, string file, string language)
void RegisterClientScriptFile(string key, string file, string language, bool defer)</pre>
<h4>Parameters</h4>
<blockquote>
	<p>key - Script key. If a script file is already registered using this key 
	then the previous script is replaced<br>
	file - The javascript include file to reference<br>
	Language - The script's language. Default is &quot;Javascript&quot;<br>
	defer - Whether or not the script should be run after the page has fully 
	loaded. Default is false</p>
</blockquote>
<h4>RegisterClientScriptEvent</h4>
<pre>void RegisterClientScriptEvent(string key, string eventName, string ctrlName, string script)
void RegisterClientScriptEvent(string key, string eventName, string ctrlName, string script, string language)</pre>
<p>Registers a client side javascript event handler. Will be rendered only for 
IE 4.0 and above.</p>
<h4>Parameters</h4>
<blockquote>
	<p>key - Script key. If a script file is already registered using this key 
	then the previous script is replaced<br>
	eventName - The event to handle<br>
	ctrlName - The name of the HTML element(s) to apply this handler to<br>
	script - The script to run<br>
	Language - The script's language. Default is &quot;Javascript&quot;</p>
</blockquote>
<h4>IsClientScriptRegistered</h4>
<p>Returns <b>true</b> if the script block is registered; otherwise, <b>false</b>.</p>
<pre>public bool IsClientScriptRegistered(string key)</pre>
<h4>Parameters</h4>
<blockquote>
	<p>key - Script key.</p>
</blockquote>
<h2>Using the class</h2>
<p>Using the class is simple. </p>
<ol>
	<li>Include the <i>ScriptPage.cs</i> file in your project<br>
	<br>
&nbsp;</li>
	<li>Derive your page from <code>CodeProject.ScriptPage </code>instead of
	<code>System.Web.UI.Page</code>.
<pre>namespace CodeProject
{
    /// &lt;summary&gt;
    /// Summary description for WebForm1.
    /// &lt;/summary&gt;
    public class WebForm1 : CodeProject.ScriptPage
    {
        ...</pre>
<li>
Include an ASP.NET Literal control named <code>_clientScript</code> at the place 
within your page where you want the script to be rendered. This can be anywhere 
on the page, but within the <code>&lt;HEAD&gt;</code> section is recommended.
<pre>&lt;HTML&gt;
&lt;HEAD&gt;
    &lt;title&gt;WebForm1&lt;/title&gt;
<b>    &lt;asp:literal id=&quot;_clientScript&quot; runat=&quot;server&quot;&gt;&lt;/asp:literal&gt;</b>
&lt;/HEAD&gt;
&lt;body&gt;

&lt;form id=Form1 ...</pre>
<p><b>Important:</b> If you don't include this control then the javascript will not be rendered.
<br><br>
<li>To register some javascript from within a page simply call the base class' 
methods:
<pre>
private void Page_Load(object sender, System.EventArgs e)
{
	// Let's add some javascript
	RegisterClientScriptBlock("Script1", "alert(\"Script1 called\");");
	RegisterClientScriptFile("Script2",  "MyScripts.js", "Javascript 1.2");
	RegisterClientScriptEvent("Script3", "onclick", "MyButton", "alert(\"Script3 called\");");
}
</pre>

<li>
To register some javascript from within a user or custom control simply cast the parent page to
the base class and again call the base class' methods:
<pre>
CodeProject.ScriptPage basePage = Page as CodeProject.ScriptPage;
if (basePage != null)
    basePage.RegisterClientScriptBlock("Script4", 
             "document.getElementById(\"MyTable\").style.backgroundColor = '#ff9900';",
             "Javascript", true);</pre>

</ol>
<h2>Results</h2>
<p>Consider the page below which contains a simple form and a simple User Control. Both the form and the user control will register some javascript as described above.
<pre lang="asp.net">
&lt;%@ Page language=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; 
         AutoEventWireup=&quot;false&quot; Inherits=&quot;CodeProject.WebForm1&quot; 
         enableViewState=&quot;False&quot; Trace=&quot;False&quot;%&gt;

&lt;%@ Register TagPrefix=&quot;CP&quot; TagName=&quot;WebUserControl1&quot; Src=&quot;WebUserControl1.ascx&quot; %&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &gt;
&lt;HTML&gt;
&lt;HEAD&gt;
   &lt;title&gt;WebForm1&lt;/title&gt;
   &lt;asp:literal id=&quot;_clientScript&quot; runat=&quot;server&quot;&gt;&lt;/asp:literal&gt;
&lt;/HEAD&gt;
&lt;body&gt;

&lt;form id=Form1 method=post runat=&quot;server&quot;&gt;
&lt;p&gt;This is a very simple webpage. Click 'View Source' to 
see the Javascript embedded within this page. 
&lt;P&gt;&lt;input type=button id=MyButton name=MyButton value=&quot;Click me&quot;&gt;&lt;/P&gt;
&lt;P&gt;&lt;CP:WebUserControl1 id=WebUserControl11 runat=&quot;server&quot;&gt;&lt;/CP:WebUserControl1&gt;&lt;/P&gt;&lt;/form&gt;

&lt;/body&gt;
&lt;/HTML&gt;</pre>

<p>The output, when rendered, is as follows:

<pre lang="html">
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &gt;
&lt;HTML&gt;
&lt;HEAD&gt;
&lt;title&gt;WebForm1&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot; language=&quot;Javascript 1.2&quot; src=&quot;MyScripts.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; language=&quot;Javascript&quot;&gt;&lt;!--
alert(&quot;Script1 called&quot;);
--&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; language=&quot;Javascript&quot; defer=&quot;true&quot;&gt;&lt;!--
document.getElementById(&quot;MyTable&quot;).style.backgroundColor = '#ff9900';
--&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; language=&quot;Javascript&quot; for=&quot;MyButton&quot; event=&quot;onclick&quot; defer=&quot;true&quot;&gt;&lt;!--
alert(&quot;Script3 called&quot;);
//--&gt;&lt;/script&gt;

&lt;/HEAD&gt;
&lt;body&gt;

&lt;form name=&quot;Form1&quot; method=&quot;post&quot; action=&quot;WebForm1.aspx&quot; id=&quot;Form1&quot;&gt;
&lt;input type=&quot;hidden&quot; name=&quot;__VIEWSTATE&quot; value=&quot;/wEQBQg0MzYwOTMxOWRk16k9eelhvHlDer9mNoFRa/lCEqA=&quot; /&gt;

&lt;p&gt;This is a very simple webpage. Click 'View Source' to 
see the Javascript embedded within this page. 
&lt;P&gt;&lt;input type=button id=MyButton name=MyButton value=&quot;Click me&quot;&gt;&lt;/P&gt;
&lt;P&gt;

&lt;table id=MyTable name=MyTable border=1 width=200 height=60 bgcolor=grey&gt;
&lt;tr&gt;&lt;td align=center valign=middle&gt;&lt;font size=2 face=verdana&gt;This is a User Control&lt;/font&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;/P&gt;&lt;/form&gt;

&lt;/body&gt;
&lt;/HTML&gt;</pre> 

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chris Maunder
Founder CodeProject
Canada Canada
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.

His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.

He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.

Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 9 Jan 2004
Article Copyright 2004 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid