How to create a complete AJAX Server Control. Part 1.

Posted on Updated on

This is the first post of a series of posts in where I’ll explain how to create an AJAX Server Control using MS AJAX Extensions and the AjaxControlToolkit (Not an Extender). I’ll be adding support to Postbacks, Callbacks, Syncronisation and other functionalities expected by our controls to make them useful in all kind of scenarios.

The control that I’m going to develop is a Shopping Cart like the one you can see in any of the online shopping web pages and I’ll be using very basic HTML and CSS style. My knowledge of CSS is quite basic so don’t expect to do very fancy styling (I’ll leave that to you).

In this first post I’m going to explain how to create the basis of the control. Just the basic required elements to have a working control, Server and Client.

Setting up the Solution and projects

Create a Solution with 2 projects, one ASP.NET AJAX Server Control in where we will add the control and one ASP.NET Web Application in where we will test it.


To simplify the work I’m going to make use of the AjaxControlToolkit library. There are a couple of Interfaces and Base classes that we can re use to avoid having to implement a lot of plumbering. Check as well that you have the Web references.


Creating the basic control

Our Ajax Server control is going to be formed by several parts:

  1. One C# class that will execute the server side of the control
  2. One JS file that will contain the client side representation of the control inside the browser
  3. One CSS file for the styles
  4. Some images used by the control

clip_image002[9] clip_image004[8]

What we have to remember is that the JS, CSS and image files are going to be embedded in the dll when we compile, so we have to go to the properties of each of the files and change the Build Action to Embedded Resource. Once we have done that we have to include them as WebReference so the files are ready to be used by the control and the Browser (We need to add [assembly: WebResource(“AjaxControl.Images.cart.png”, “img/png”)] directives for each of the files as shown in the following example).


using AjaxControlToolkit;

// In the properties of the element set: Build Action -> Embedded Resource
[assembly: WebResource("AjaxControl.Images.cart.png", "img/png")]
[assembly: WebResource("AjaxControl.ShoppingCart.js", "application/x-javascript")]
[assembly: WebResource("AjaxControl.ShoppingCart.css", "text/css", PerformSubstitution = true)]

namespace AjaxControl
	public class ShoppingCart : ScriptControlBase
		const string ShoppingCartCSS = "ShoppingCart";

		public ShoppingCart(): base(false, HtmlTextWriterTag.Div)
			this.Attributes["class"] = ShoppingCartCSS;

		#region Control Rendering

		protected override void OnPreRender(EventArgs e)
			if (!this.DesignMode)
				if (ScriptManager.GetCurrent(Page) == null)
					throw new HttpException("A ScriptManager control must exist on the current page.");

		private void InitialiseControls()
			Image cartImage = new Image();
			cartImage.ID = "cartImage";
			cartImage.Attributes["class"] = "cartImage";
			cartImage.ToolTip = "Shopping Cart";
			cartImage.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(),"AjaxControl.Images.cart.png");


In the sample we can see that the control inherits from AjaxControlToolkit.ScriptControlBase. This class inherits from public abstract class ScriptControl : WebControl, IScriptControl and gives us an implementation of the abstract methods IEnumerable<ScriptDescriptor> GetScriptDescriptors() and IEnumerable<ScriptReference> GetScriptReferences() that allows us to use the attributes [ClientCssResource] and [ClientScriptResource] to define our JS and CSS Resources in a declarative way.

To be able to use the images in the browser we can use Image controls and set the property ImageUrl = Page.ClientScript.GetWebResourceUrl(…) To generate an URL that will be used by the Browser to download the image file from the embedded objects in the DLL.

To do some work in the browser (AJAX functionality) we need to add the JS class that will handle all the functionality in the client side.

1. We first need to register the namespace of the control and create the constructor of the control.

2. Then we need to register the class at the end of the implementation, in where we specify that we are extending from Sys.UI.Control and that we will implement the Sys.IDisposable interface.

3. To finish we implement the initialize and dispose methods.

4. All the methods call the base methods to initialise the parent class.

Inheritance in JS it’s been added by MS AJAX Framework as a pattern and it’s a convention (it’s required to add certain lines of code to make it work in different locations and if you don’t do it, it won’t work as expected).




// Class Constructor:
// Will be called by the MS Ajax Framework to construct the client side reperentation of the control
var $ShoppingCart = AjaxControl.ShoppingCart = function(element)
	AjaxControl.ShoppingCart.initializeBase(this, [element]);

// Control Initialisation and Destruction--------------------------------------
$ShoppingCart.prototype.initialize = function()
	$ShoppingCart.callBaseMethod(this, "initialize");

// As the control implements Sys.IDisposable, the MS Ajax Framework requires of this method.
// This method will be use release used resources (specially required to work with Update Panels)
$ShoppingCart.prototype.dispose = function()
	$ShoppingCart.callBaseMethod(this, 'dispose');

//Register the ShoppingCart class with the client AJAX library and specify its base class as Sys.UI.Control.
$ShoppingCart.registerClass('AjaxControl.ShoppingCart', Sys.UI.Control, Sys.IDisposable);


	padding: 2px;
	border: thin dotted #FF0000;
	background-color: #FFFF00;

Now it’s time to use the control in a web page. To do that, in the web project we add references to the project and the AjaxControlToolkit.dll. We can add the control directly to the page or use the Toolbox in VS to drag and drop the control to the page in Design mode.



Have a look at the rendered HTML in the code. The links to the JS code, images… are generated as src=”/WebResource.axd?…” and =”/ScriptResource.axd?…”. Notice that not only your JS code is being referenced. MS AJAX JS libraries and the AjaxControlToolkit are downloaded as well.

Another piece of automatically generated piece of code is the creation of your control ($create). After the page is rendered an instance of your control in the client is created for you.

Rendered HTML:


<div id="Cart1" class="ShoppingCart" style="height:40px;width:40px;">
	   <img title="Shopping Cart" class="cartImage" src="/WebResource.axd?d=JwQFLCZRRtnD8Q0&amp;t=633807629642435710" style="border-width:0;" /></div>


Awesome, now we have the base of our Ajax Server Control that looks like the ones published in the AjaxControlToolkit.

You can download the code here.

Important: I couldn’t upload the file as it was a zip file, so I added the extension jpg. After saving the file, remove the extension and unzip it normally.

2 thoughts on “How to create a complete AJAX Server Control. Part 1.

    chart said:
    September 1, 2009 at 04:24
    Ankit Singh said:
    January 5, 2012 at 07:59


    I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of ASP.Net AJAX Server Control: UpdateProgress, UpdatePanel and it helped me a lot. Thanks for sharing with us. Check out this link too its also having nice post with wonderful explanation on ASP.Net AJAX Server Control: UpdateProgress, UpdatePanel…….,%20UpdatePanel

    Thanks Everyone for your nice precious post.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s