Click here to Skip to main content
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
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
using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeProject
{
	/// <summary>
	/// A base page class from which all web pages can be derived. The main
	/// purpose of this class is to provide more complete handling of client
	/// side javascript rendering.
	/// </summary>
	public class ScriptPage : System.Web.UI.Page
	{
		protected Hashtable	m_ClientScripts;		// Set of client side scripts to output in HTML header
		public    Literal   _clientScript;			// Placeholder for script output in the webpage

		/// <summary>
		/// Constructor
		/// </summary>
		public ScriptPage() : base()
		{
			m_ClientScripts = new Hashtable();
		}

		#region Protected methods
		/// <summary>
		/// Send a trace statement to the Trace Context
		/// </summary>
		/// <param name="str">String to output</param>
		protected void DbgTrace(string str)
		{
			if (HttpContext.Current != null && Trace != null && Trace.IsEnabled)
			{
				Trace.Write(ToString(), str);
			}
		}

		/// <summary>
		/// Gets the complete HTML describing the client-side scripts to output as part
		/// of this page's headers
		/// </summary>
		protected string ClientScript
		{
			get
			{
				StringBuilder script = new StringBuilder();

				if (m_ClientScripts != null)
					foreach (object scriptBlock in m_ClientScripts.Values)
						script.Append(scriptBlock.ToString() + "\n");

				//DbgTrace("ClientScript is " + script.ToString());

				return script.ToString();
			}
		}
		#endregion

		#region Public methods

		/// <summary>
		/// Registers a client side javascript event handler
		/// </summary>
		/// <param name="key">script key. If a script is already registered using this key then the 
		/// previous script is replaced</param>
		/// <param name="eventName">The event to handle</param>
		/// <param name="ctrlName">The name of the HTML element(s) to apply this handler to</param>
		/// <param name="script">The script to run</param>
		public virtual void RegisterClientScriptEvent(string key, string eventName, string ctrlName, string script)
		{
			RegisterClientScriptEvent(key, eventName, ctrlName, script, "Javascript");
		}

		/// <summary>
		/// Registers a client side javascript event handler
		/// </summary>
		/// <param name="key">script key. If a script is already registered using this key then the 
		/// previous script is replaced</param>
		/// <param name="eventName">The event to handle</param>
		/// <param name="ctrlName">The name of the HTML element(s) to apply this handler to</param>
		/// <param name="script">The script to run</param>
		/// <param name="language">The script's language</param>
		public virtual void RegisterClientScriptEvent(string key, string eventName, string ctrlName, string script, 
			                                          string language)
		{
			// client-side event handling only in IE 4 and above
			if (Request.Browser.Browser.ToUpper().IndexOf("IE") < 0 || 
				Double.Parse(Request.Browser.Version) < 4.0)
				return;

			StringBuilder block = new StringBuilder();
			block.Append("<script type=\"text/javascript\" language=\"");
			block.Append(language);
			block.Append("\" for=\"");
			block.Append(ctrlName);
			block.Append("\" event=\"");
			block.Append(eventName);
			block.Append("\" defer=\"true\"><!--\n");
			block.Append(script);
			block.Append("\n//--></script>");

			if (!m_ClientScripts.ContainsKey(key))
			{
				m_ClientScripts.Add(key, block);
				//DbgTrace("Adding script: " + key + " - " + block);
			}
			else
			{
				m_ClientScripts[key] = block;
				//DbgTrace("Replacing file: " + key + " - " + block);
			}
		}

		/// <summary>
		/// Registers a client side javascript file include
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="file">The javascript include file to reference</param>
		public virtual void RegisterClientScriptFile(string key, string file)
		{
			RegisterClientScriptFile(key, file, "Javascript", false);
		}

		/// <summary>
		/// Registers a client side javascript file include
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="file">The javascript include file to reference</param>
		/// <param name="language">The script's language</param>
		public virtual void RegisterClientScriptFile(string key, string file, string language)
		{
			RegisterClientScriptFile(key, file, language, false);
		}

		/// <summary>
		/// Registers a client side javascript file include
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="file">The javascript include file to reference</param>
		/// <param name="language">The script's language</param>
		/// <param name="defer">Whether or not the script should be run after the page has fully loaded</param>
		public virtual void RegisterClientScriptFile(string key, string file, string language, bool defer)
		{
			StringBuilder block = new StringBuilder();
			block.Append("<script type=\"text/javascript\" language=\"");
			block.Append(language);
			block.Append("\" src=\"");
			block.Append(file);
			if (defer) block.Append(" defer=\"true\"");
			block.Append("\"></script>");

			if (!m_ClientScripts.ContainsKey(key))
			{
				m_ClientScripts.Add(key, block);
				//DbgTrace("Adding file: " + key + " - " + File);
			}
			else
			{
				m_ClientScripts[key] = block;
				//DbgTrace("Replacing file: " + key + " - " + File);
			}
		}

		/// <summary>
		/// Registers a client side javascript block. The block is automatically surrounded by &lt;script> tags
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="script">The javascript to include.</param>
		public override void RegisterClientScriptBlock(string key, string script)
		{
			RegisterClientScriptBlock(key, script, "Javascript", false);
		}

		/// <summary>
		/// Registers a client side javascript block. The block is automatically surrounded by &lt;script> tags
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="script">The javascript to include.</param>
		/// <param name="language">The script's language</param>
		public virtual void RegisterClientScriptBlock(string key, string script, string language)
		{
			RegisterClientScriptBlock(key, script, language, false);
		}

		/// <summary>
		/// Registers a client side javascript block. The block is automatically surrounded by &lt;script> tags
		/// </summary>
		/// <param name="key">Script key. If a script file is already registered using this key then the previous script is replaced</param>
		/// <param name="script">The javascript to include.</param>
		/// <param name="language">The script's language</param>
		/// <param name="defer">Whether or not the script should be run after the page has fully loaded</param>
		public virtual void RegisterClientScriptBlock(string key, string script, string language, bool defer)
		{
			StringBuilder block = new StringBuilder();
			block.Append("<script type=\"text/javascript\" language=\"");
			block.Append(language);
			block.Append("\"");
			if (defer) block.Append(" defer=\"true\"");
			block.Append("><!--\n");
			block.Append(script);
			block.Append("\n--></script>");

			if (!m_ClientScripts.ContainsKey(key))
			{
				m_ClientScripts.Add(key, block);
				//DbgTrace("Adding script: " + key + " - " + script);
			}
			else
			{
				m_ClientScripts[key] = block;
				//DbgTrace("Replacing script: " + key + " - " + script);
			}
		}

		public bool IsClientScriptRegistered(string key)
		{
			return m_ClientScripts.ContainsKey(key);
		}
		#endregion

		/// <summary>
		/// Called just before the page is rendered. All components within this page will
		/// have registered client scripts by now, so we take the chance to set the ClientScript
		/// property of the header control as the collective client script for this page.
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e)
		{
			// We need to dump the client-side script into an ASP.NET Literal control
			// called "_clientScript". If this hasn't been added to the form then we
			// just create a dummy and set it as invisible.
			if (_clientScript == null)
			{
				_clientScript = new Literal();
				_clientScript.Visible = false;
			}
			else
				_clientScript.Text = ClientScript;

			base.OnPreRender(e);

//			if (Controls.Contains(_clientScript))
//				_clientScript.Text = ClientScript;
		}
	}
}

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.
Follow on   Twitter   Google+   LinkedIn

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