Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET
Article

An improvement to RegisterClientScriptBlock

Rate me:
Please Sign up or sign in to vote.
4.76/5 (33 votes)
8 Jan 2004CPOL4 min read 288.8K   2.3K   106   33
A simpler and more flexible method of registering client-side Javascript within ASP.NET pages and controls.

Sample Image - scriptregister.gif

Introduction

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 HEAD tags of a page, where appropriate, but ASP 3.0 didn't provide an easy solution.

ASP.NET does provide a solution, of sorts, in the form of the RegisterClientScriptBlock method in the Page 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 "of sorts" because while it's a neat idea, it doesn't actually do what you would always hope.

The issues, at least for me, of the RegisterClientScriptBlock method were that the script is output after the opening Form 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 <script> 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.

A new base class for your webpages.

With ASP.NET providing the ability to derive your pages from whatever System.Web.UI.Page 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 System.Web.UI.Page derived class, but I'm lazy and so that particular exercise has been left to the reader.

I instead created a simple class, ScriptPage, derived from System.Web.UI.Page from which subsequent pages can be derived. The methods available are:

RegisterClientScriptBlock

Registers a client side javascript block. The block is automatically surrounded by <script> tags

C#
void RegisterClientScriptBlock(string key, string script)
void RegisterClientScriptBlock(string key, string script, string language)
void RegisterClientScriptBlock(string key, string script, string language, 
                               bool defer)

Parameters

key - Script key. If a script file is already registered using this key then the previous script is replaced
script - The javascript to include.
language - The script's language. Default is "Javascript"
defer - Whether or not the script should be run after the page has fully loaded. Default is false

RegisterClientScriptFile

Registers a client side javascript file include

C#
void RegisterClientScriptFile(string key, string file)
void RegisterClientScriptFile(string key, string file, string language)
void RegisterClientScriptFile(string key, string file, string language, 
                              bool defer)

Parameters

key - Script key. If a script file is already registered using this key then the previous script is replaced
file - The javascript include file to reference
language - The script's language. Default is "Javascript"
defer - Whether or not the script should be run after the page has fully loaded. Default is false

RegisterClientScriptEvent

C#
void RegisterClientScriptEvent(string key, string eventName, string ctrlName,
                               string script)
void RegisterClientScriptEvent(string key, string eventName, string ctrlName, 
                               string script, string language)

Registers a client side javascript event handler. Will be rendered only for IE 4.0 and above.

Parameters

key - Script key. If a script file is already registered using this key then the previous script is replaced
eventName - The event to handle
ctrlName - The name of the HTML element(s) to apply this handler to
script - The script to run
language - The script's language. Default is "Javascript"

IsClientScriptRegistered

Returns true if the script block is registered; otherwise, false.

C#
public bool IsClientScriptRegistered(string key)

Parameters

key - Script key to check.

Using the class

Using the class is simple.

  1. Include the ScriptPage.cs file in your project

  2. Derive your page from CodeProject.ScriptPage instead of System.Web.UI.Page.
    C#
    namespace CodeProject
    {
        /// <summary>
        /// Summary description for WebForm1.
        /// </summary>
        public class WebForm1 : CodeProject.ScriptPage
        {
            ...
  3. Include an ASP.NET Literal control named _clientScript at the place within your page where you want the script to be rendered. This can be anywhere on the page, but within the <HEAD> section is recommended.
    ASP.NET
    <HTML>
    <HEAD>
        <title>WebForm1</title>
        <asp:literal id="_clientScript" runat="server"></asp:literal>
    </HEAD>
    <body>
    
    <form id=Form1 ...

    Important: If you don't include this control then the javascript will not be rendered.

    Note: The designer in Visual Studio .NET will, if you edit your page in design mode, add the following line your code-behind class:

    C#
    protected System.Web.UI.WebControls.Literal _clientScript;

    If this occurs you will need to manually remove this line from your code-behind file.

  4. To register some javascript from within a page simply call the base class' methods:
    C#
    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\");");
    }
  5. 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:
    C#
    CodeProject.ScriptPage basePage = Page as CodeProject.ScriptPage;
    if (basePage != null)
     basePage.RegisterClientScriptBlock("Script4", 
      "document.getElementById(\"MyTable\").style.backgroundColor='#ff9900';",
      "Javascript", true);

Results

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.

ASP.NET
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" 
         AutoEventWireup="false" Inherits="CodeProject.WebForm1" 
         enableViewState="False" Trace="False"%>

<%@ Register TagPrefix="CP" TagName="WebUserControl1" 
    Src="WebUserControl1.ascx" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
   <title>WebForm1</title>
   <asp:literal id="_clientScript" runat="server"></asp:literal>
</HEAD>
<body>

<form id=Form1 method=post runat="server">

<p>This is a very simple webpage. Click 'View Source' to 
see the Javascript embedded within this page.

<P><input type=button id=MyButton name=MyButton value="Click me"></P>
 
<CP:WebUserControl1 id=WebUserControl11 runat="server"></CP:WebUserControl1>
 
</form>

</body>
</HTML>

The output, when rendered, is as follows:

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

</HEAD>
<body>

<form name="Form1" method="post" action="WebForm1.aspx" id="Form1">

<p>This is a very simple webpage. Click 'View Source' to 
see the Javascript embedded within this page.
 
<P><input type=button id=MyButton name=MyButton value="Click me"></P>

<table id=MyTable name=MyTable border=1 width=200 height=60 
       bgcolor=grey>
<tr><td align=center valign=middle><font size=2 face=verdana>This 
is a User Control</font></td></tr>
</table>

</form>

</body>
</HTML>

License

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


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
GeneralImprovement for ASP.NET 2.0 Pin
Matthias Hertel29-Aug-05 4:06
professionalMatthias Hertel29-Aug-05 4:06 
GeneralRe: Improvement for ASP.NET 2.0 Pin
mikeward0015-Mar-07 12:13
mikeward0015-Mar-07 12:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.