Click here to Skip to main content
15,891,253 members
Articles / Web Development / ASP.NET

An improvement to RegisterClientScriptBlock

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


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