Download the source code for this demo here.
Introduction
The demand for high quality web interfaces is continually increasing. The movement towards Web 2.0 places an increasing emphasis in making a web application look and feel like it were a home desktop application, with all the bells and whistles attached. Users expect each page they visit to interact with them in a smooth and natural way.
Asynchronous JavaScript and XML, AJAX, is one tool that helps to create this user experience. In a typical scenario, JavaScript on the page sends and retrieves data from the web server asynchronously, updating the web page without flicker and with minimal delay. Google Inc.'s GMail is an example. Each GMail page retrieves content from GMail only a portion at a time, "on demand". The entire experience is seamless.
Microsoft recently released a framework for AJAX, and a corresponding collection of control extenders called the AJAX Control Toolkit. The toolkit contains several control extenders. An AJAX control extender adds AJAX functionality to a non-ajax web control. The extender approach can be particularly useful when there is a requirement to add similar AJAX behavior to more than one control type, such as adding behaviors to buttons, images, and panels.
This tutorial introduces the basics of creating a custom AJAX control extender. We discuss embedded resources, property decorations (attributes), and client-side Web service calls.
The Scenario
Consider a form built for a web application. The form contains several places for input. From time to time, users flood you with questions about the meaning of each element. You want to add some context sensitive help to the page to spare yourself all the most frequently asked questions, saving both time and money.
We'll create a very simple AJAX control extender that wraps a server control, such as a Button or a Label, and adds context sensitive help at the click of a mouse. Moreover, the extender will populate the help with the results of a web service call to separate the content from the functionality.
Getting Started
Below is an example of the body of a very simple page. There are three main elements. On each, we want to add context sensitive help. The fourth element, the Panel at the bottom, is a placeholder for our help content.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Looking for help..."/>
<br />
<br />
<asp:Image ID="Image1" runat="server" ImageUrl="~/flower.jpg" />
<br />
<br />
<asp:Panel ID="Panel1" runat="server">
This is the content of the panel.<br />
If you would like to find help, kindly click among this text.<br />
Good luck!
</asp:Panel>
<br />
<br />
<asp:Panel ID="HelpPanel" runat="server" />
<br />
<br />
</form>
To make our control extender consumable from any website, we'll compile the extender into a separate assembly. To do this, first make sure that the extender templates are installed. Download the AJAX control toolkit from http://ajax.asp.net, extract the files into the directory of choice, and execute the .vsi installers located in the archive at AjaxControlExtender\AjaxControlExtender.vsi. Once this is installed, add the new extender project to your Visual Studio solution by right clicking on the solution and selecting Add -> New Project, or selecting File -> Add -> New Project from the menu.
Select ASP.NET AJAX Control Project from the templates.
Delete the default .cs and .js files, and create a directory, Help to hold the new control. Right click on the folder, select Add -> New Item, and select ASP.NET AJAX Extender Control from the templates. Name the control "Help", since the convention of "HelpExtender" is added by default.
We now have the basic file structure for the control.
Configuring the Namespaces
It is important to give some thought to the namespace conventions for your control. There are three namespaces of immediate concern:
- The namespace of your server code
- The namespace of your client JavaScript
- The default namespace of your assembly
Adjusting the namespace of server code is plain and direct. I chose KbrProductions.Web.Extensions, after the pattern set by Microsoft's System.Web.Extensions. The client namespace is adjusted in the .js file. For this project the client namespace is KbrProductions.Ajax. A simple search and replace can fix the handful of references. Finally, the default namespace of the assembly can be configured by right clicking on the project file, selecting Properties, and editing the namespace in the Application tab. This namespace is important because it influences embedded resources.
For the JavaScript file to be consumable by the website, we must include it as a resource to the project assembly. Do this by selecting the file in Solution Explorer, viewing its properties, and setting the Build Action attribute to Embedded Resource.
Now visit the HelpExtender.cs file. Edit the assembly attribute to read:
[assembly: System.Web.UI.WebResource(
"KbrProductions.Web.Extensions.Help.HelpBehavior.js",
"text/javascript")]
The first parameter is a resource path for the javascript file. The naming convention for the path is: [Assembly Namespace][.directory][.FileName]. Remember, the assembly namespace is the default namespace set in the project properties. For the directory, use dots (.) to separate folders instead of backslashes. Misconfiguring this line is the common cause of the following web page error:
Assembly 'Extensions, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' contains a Web resource with name 'Extensions.Help.HelpBehavior.js', but does not contain an embedded resource with name 'Extensions.Help.HelpBehavior.js'.
When in doubt, fire up ILDASM and view the contents of the control assembly. The manifest contains the proper path for the JavaScript file on a .mresource line.
The extender class includes the JavaScript file by means of a ClientScriptResource decoration. Modify the decoration as shown below, where the first string indicates the client class name, and the second string specifies the resource exactly as specified in the assembly attribute earlier in the page.
[ClientScriptResource(
"KbrProductions.Ajax.HelpBehavior",
"KbrProductions.Web.Extensions.Help.HelpBehavior.js")]
At this point, the namespaces of the control assembly should be configured.
Server-Side Extender Properties
Next, we'll specify the properties that will be available as attributes to our extender markup. Because we inherit from ExtenderControlBase, we already have a TargetControlID property, which we can use to specify the control we want to extend.
We also want to specify the control that will contain the contents of our help. We decorate the property with the IDReferenceProperty attribute to enable the extender to automatically resolve the specified ID into a ClientID.
/// <summary>
/// ID of the control that will contain the help content.
/// </summary>
[ExtenderControlProperty]
[DefaultValue("")]
[IDReferenceProperty(typeof(WebControl))]
[ClientPropertyName("helpPanelID")]
public string HelpPanelID
{
get { return GetPropertyValue("HelpPanelID", ""); }
set { SetPropertyValue("HelpPanelID", value); }
}
Next, we'll build properties to define the location of a Web service that provides the text for the context-sensitive help. We decorate this property as a UrlProperty, which provides automatic resolving of server-relative URLs, that is, any URL starting with "~/". We also decorate it with a TypeConverter to handle some Web service specific url handling.
/// <summary>
/// Path to the webservice that the extender will pull the images from.
/// </summary>
[UrlProperty()]
[ExtenderControlProperty()]
[TypeConverter(typeof(ServicePathConverter))]
[ClientPropertyName("servicePath")]
public string ServicePath
{
get { return GetPropertyValue("ServicePath", ""); }
set { SetPropertyValue("ServicePath", value); }
}
Next we add a required property to define which method should be called.
/// <summary>
/// The webservice method that will be called to supply help.
/// </summary>
[ExtenderControlProperty]
[RequiredProperty]
[DefaultValue("")]
[ClientPropertyName("serviceMethod")]
public string ServiceMethod
{
get { return GetPropertyValue("ServiceMethod", ""); }
set { SetPropertyValue("ServiceMethod", value); }
}
And, finally, we add a property to define a parameter for the Web service call. We could treat this parameter as a key to determine which piece of help to return from the service.
/// <summary>
/// Context key to pass to the service method to get help text.
/// </summary>
[ExtenderControlProperty]
[DefaultValue("")]
[ClientPropertyName("helpContextKey")]
public string HelpContextKey
{
get { return GetPropertyValue("HelpContextKey", ""); }
set { SetPropertyValue("HelpContextKey", value); }
}
The next step is to provide a client-side equivalent interface to these properties.
Client-Side Extender Properties
Basic handling of each property from JavaScript is made extremely simple due to the AJAX Control Toolkit. All that is required is to add variable declarations to the constructor function, and add get/set functions to the object prototype. It is important to note that the property names for the get and set functions are case sensitive and should reflect the ClientPropertyName configured in the server-side extender code. Additional utility variables can be added to the constructor function as well.
KbrProductions.Ajax.HelpBehavior = function(element) {
KbrProductions.Ajax.HelpBehavior.initializeBase(this, [element]);
this._helpContextKey = null; // HelpContextKey property
this._serviceMethod = null; // ServiceMethod property
this._servicePath = null; // ServicePath property
this._helpPanelID = null; // HelpPanelID property
this._helpPanel = null; // HelpPanel element
this._clickHandler = null; // Click Event handler for the extended control
this._targetElement = null; // Element of the extended control
}
KbrProductions.Ajax.HelpBehavior.prototype = {
// ...
// extended properties
get_serviceMethod : function() { return this._serviceMethod; },
set_serviceMethod : function(value) { this._serviceMethod = value; },
get_servicePath : function() { return this._servicePath; },
set_servicePath : function(value) { this._servicePath = value; },
get_helpContextKey : function() { return this._helpContextKey; },
set_helpContextKey : function(value) { this._helpContextKey = value; },
get_helpPanelID : function() { return this._helpPanelID; },
set_helpPanelID : function(value) { this._helpPanelID = value; }
}
Fleshing out the Client Behavior
All that remains to complete our extender is to implement the client behavior. To provide feedback to the user that a control contains help, change the mouse cursor of the extended element. The object prototype's initialize method is a good place to do this.
initialize : function() {
KbrProductions.Ajax.HelpBehavior.callBaseMethod(this, 'initialize');
// Apply the CSS cursor style, "help"
this._targetElement = this.get_element();
this._targetElement.style.cursor = "help";
// ...
Next, wire up an event handler in the initialize function to handle the click event of the target element. Use the Function.createDelegate method to create the handler. This ensures that multiple handlers can potentially be attached to the element without conflicting.
// Attach an event handler to the click event of the element
if(this._targetElement) {
this._clickHandler = Function.createDelegate(this, this._onClick);
$addHandler(this._targetElement, 'click', this._clickHandler);
}
Add functionality to the dispose method to clean up the event handler. This is good practice to keep our memory clean.
dispose : function() {
// Remove the event handler from the element if attached.
if(this._clickHandler) {
$removeHandler(this._targetElement, 'click', this._clickHandler);
this._clickHandler = null;
}
KbrProductions.Ajax.HelpBehavior.callBaseMethod(this, 'dispose');
},
We now create the this._onClick function to handle the mouse click. We first implement a few lines to prevent any full-page postback that might occur. Parameters to the service method should be prepared as a dictionary key-value pair. We then can invoke the method using the ASP.NET AJAX Sys.Net.WebServiceProxy.invoke method. The method has seven parameters:
- The path to the Web service.
- The method to invoke.
- A parameter to indicate whether the call should use HTTP POST. For security reasons, this defaults to
false.
- The parameters for the method.
- An event handler to be called when the service call returns successfully.
- An event handler to be called if the service call fails.
- Any JavaScript structure to pass to the event handler. This is a place holder if you want to send more than the defaults.
// click event for the extended element
_onClick : function(e) {
// prevent post back.
e.preventDefault();
e.stopPropagation();
// prepare parameters, if necessary
var params = null;
if (this._helpContextKey) {
params = { 'helpContextKey' : this._helpContextKey };
}
// Invoke the web service
Sys.Net.WebServiceProxy.invoke(
this._servicePath, // Service path
this._serviceMethod, // Service method
false, // use POST (default false)
params, // params
Function.createDelegate(this, this._onServiceReply), // on success
null, // on failure
null); // additional context
},
The last addition to the script is the this._onServiceReplay handler. The toolkit uses sender and eventArgs as parameters to the method. I think they're misnamed, because the object coming in through the sender parameter is the server reply; a string. At any rate, we fill our help panel with the contents of the reply.
// reply event for the service call
_onServiceReply : function(sender, eventArgs) {
document.getElementById(this._helpPanelID).innerHTML = sender;
}
At this point, we completed all the code for the extender. All that remains is to reference this assembly by the website and add our extender to the page.
Using the Help Extender
Building the extender took a fair handful of code lines, but it all pays off when we start using the extender in the Web site. Add a reference to the extender project, and add the folling line to the <system.web><pages><controls> element of the Web.config file:
<add tagPrefix="kbr"
namespace="KbrProductions.Web.Extensions"
assembly="Extensions"/>
Note that the application will need references to the ASP.NET AJAX assembly and the AJAX Control Toolkit as well. Add a ScriptManager to the page, and extenders for the Button, Image and Panel.
<kbr:HelpExtender ID="help1" runat="server"
TargetControlID="Button1"
HelpContextKey="1"
HelpPanelID="HelpPanel"
ServiceMethod="GetHelp" />
<kbr:HelpExtender ID="help2" runat="server"
TargetControlID="Image1"
HelpContextKey="2"
HelpPanelID="HelpPanel"
ServiceMethod="GetHelp" />
<kbr:HelpExtender ID="help3" runat="server"
TargetControlID="Panel1"
HelpContextKey="3"
HelpPanelID="HelpPanel"
ServiceMethod="GetHelp" />
All that remains is to define the Web service that provides our help. We'll inject an AJAX-friendly service method right into this page. In a more practical application, the if/else if structure could be replaced with database access, file IO, or any other data retrieval. All that is required is that the method is static, takes the appropriate parameters, and returns the expected string result.
<script runat="Server" type="text/C#">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetHelp(string helpContextKey)
{
if (helpContextKey == "1")
return "There is help awaiting you.";
else if (helpContextKey == "2")
return "Excellent clicking, friend!";
else
return "There is no help found for the likes of you.";
}
</script>
Running the page now shows that each control has a help cursor. When clicked, JavaScript issues an asynchronous Web service call which populates a portion of the page with context-sensitive help. The control extender is finished.
Conclusion
ASP.NET AJAX is an excellent tool to provide a richer experience to the user by taking advantage of the control extender model and asynchronous callbacks. With a little footwork, it is possible to create extenders that add complex behaviors to a variety of server controls, potentially saving considerable effort down the road. The AJAX Control Toolkit provides classes that simplify the process of creating your own extenders. Also, because the AJAX Control Toolkit is open source, you can download the existing control extenders and add behaviors to them, as well.
Happy Coding!