Click here to Skip to main content
15,895,777 members
Articles / Web Development / HTML

Magic AJAX: Applying AJAX to your existing Web Pages

Rate me:
Please Sign up or sign in to vote.
4.82/5 (72 votes)
28 May 2007MIT12 min read 982.1K   2.7K   251  
How to apply AJAX technologies to your web pages without replacing ASP.NET controls and/or writing JavaScript code.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;

namespace MagicAjax.UI.Controls
{
	#region Class KeyPressEventArgs
	public class KeyPressEventArgs : EventArgs
	{
		private char _keyChar;

		public char KeyChar
		{
			get { return _keyChar; }
		}

		public KeyPressEventArgs (char keyChar)
		{
			this._keyChar = keyChar;
		}
	}
	#endregion

	#region Class KeyEventArgs
	public class KeyEventArgs : EventArgs
	{
		private int _keyCode;
		private bool _alt, _control, _shift;

		public int KeyCode
		{
			get { return _keyCode; }
		}

		public bool Alt
		{
			get { return _alt; }
		}

		public bool Control
		{
			get { return _control; }
		}

		public bool Shift
		{
			get { return _shift; }
		}

		public KeyEventArgs (int keyCode, bool alt, bool control, bool shift)
		{
			this._keyCode = keyCode;
			this._alt = alt;
			this._control = control;
			this._shift = shift;
		}
	}
	#endregion

	public delegate void KeyPressEventHandler (object sender, KeyPressEventArgs e);
	public delegate void KeyEventHandler (object sender, KeyEventArgs e);

	/// <summary>
	/// Captures the KeyPress, KeyDown, and KeyUp client events of its inner controls.
	/// </summary>
	/// <remarks>
	/// The KeyPress event has the IE behaviour across all browsers (invoked when a character
	/// is typed or Enter is pressed).
	/// </remarks>
	[ToolboxData("<{0}:KeyClientEventWrapper runat=server>Insert controls to capture their OnKey events</{0}:KeyClientEventWrapper>")]
	public class KeyClientEventWrapper : BaseClientEventWrapper
	{
		public event KeyPressEventHandler KeyPress;
		public event KeyEventHandler KeyDown;
		public event KeyEventHandler KeyUp;

		protected override void HandleEvent(string eventName, string argument)
		{
			switch (eventName)
			{
				case "keypress" :
					OnKeyPress (new KeyPressEventArgs((char)Int32.Parse(argument)));
					break;

				case "keydown" :
					OnKeyDown (CreateKeyEventArgs(argument));
					break;

				case "keyup" :
					OnKeyUp (CreateKeyEventArgs(argument));
					break;

				default:
					throw new MagicAjaxException(String.Format("Invalid event name '{0}' captured by {1}.", eventName, ClientID));
			}
		}

		protected override void AttachClientEvents(HtmlTextWriter writer)
		{
			if ( KeyPress != null )
				writer.AddAttribute ("onkeypress", String.Format("__onKeyPress(event,'{0}');", UniqueID));

			if ( KeyDown != null )
				writer.AddAttribute ("onkeydown", String.Format("__onKeyUpDown(event,'keydown','{0}');", UniqueID));

			if ( KeyUp != null )
				writer.AddAttribute ("onkeyup", String.Format("__onKeyUpDown(event,'keyup','{0}');", UniqueID));
		}

		protected override void OnPreRender(EventArgs e)
		{
			string onKeyScript = @"<script type='text/javascript'>
				<!--
				function __onKeyPress(e,src)
				{
					if ('which' in e && e.keyCode!=13)
					{
						if (e.which>=32)
							__doPostBack(src,'keypress;'+e.which);
					}
					else
					{
						__doPostBack(src,'keypress;'+e.keyCode);
					}
				}
				function __onKeyUpDown(e,evtname,src)
				{
					__doPostBack(src,evtname+';'+e.keyCode+','+e.altKey+','+e.ctrlKey+','+e.shiftKey);
				}
				// -->
				</script>";

			base.OnPreRender (e);
			if ( ! Page.IsClientScriptBlockRegistered("__ONKEYBLOCK") )
				Page.RegisterClientScriptBlock("__ONKEYBLOCK", onKeyScript);
		}

		protected virtual KeyEventArgs CreateKeyEventArgs (string argument)
		{
			int keyCode;
			bool alt, control, shift;

			try
			{
				string[] args = argument.Split(',');
                keyCode = Int32.Parse(args[0]);
				alt = Boolean.Parse(args[1]);
				control = Boolean.Parse(args[2]);
				shift = Boolean.Parse(args[3]);

				return new KeyEventArgs(keyCode, alt, control, shift);
			}
			catch
			{
				throw new MagicAjaxException(String.Format("Invalide KeyEvent argument '{0}' for {1}.", argument, ClientID));
			}
		}

		protected virtual void OnKeyPress (KeyPressEventArgs e)
		{
			if (KeyPress != null)
				KeyPress (this, e);
		}

		protected virtual void OnKeyDown (KeyEventArgs e)
		{
			if (KeyDown != null)
				KeyDown (this, e);
		}

		protected virtual void OnKeyUp (KeyEventArgs e)
		{
			if (KeyUp != null)
				KeyUp (this, e);
		}
	}
}

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 MIT License


Written By
Web Developer
Greece Greece
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions