Building ASP.NET Ajax Custom Controls

In this article I will take you through the creation of ASP.NET Ajax Custom Client Controls. ASP.NET allows you to create your own AJAX client controls which can be any one of the following.

1. Background client functionality (No UI impact. An ideal example would be a ASP.NET AJAX timer control)

2. Custom Client Controls (Displayed on the UI. Like a custom TextBox)

3. Custom Extenders (Extenders for the existing AJAX controls)

This article will include the steps involved in creating an AJAX custom client control entirely through client javascript and the steps involved in using it on the client web page.

For demonstration purposes I will create a TextBox client control, which will change its style during focus and on blur.

Creating an Ajax Custom Client Control

To create a custom client control you can make use of the existing AJAX methods like get_element(), etc, since all the AJAX libraries will be loaded onto the web page at runtime. There are several steps involved in creating an AJAX Custom Client Control. Below is the summary of it.

1. Register a namespace.

Type.registerNamespace("CustomClientControlDemo");

2. Define a class and initialize it.

//Define a class
CustomClientControlDemo.CustomAjaxTextBox = function (element) {
    CustomClientControlDemo.CustomAjaxTextBox.InitializeBase(this, [element]);
}

3. Define the prototype for the class.

4. Bind the required event handlers for the client events.

5. Register the class, which derives from Sys.UI.Control as shown below.

//Register the class deriving from Sys.UI.Control
CustomClientControlDemo.CustomAjaxTextBox.registerClass('CustomClientControlDemo.CustomAjaxTextBox', Sys.UI.Control);

Now create an empty ASP.NET web application and add a script file named CustomAjaxTextBox.js. Here is the complete javascript control class for the demo application.

//Register a namespace
Type.registerNamespace("CustomClientControlDemo");
 
//Define a class
CustomClientControlDemo.CustomAjaxTextBox = function (element) {
    CustomClientControlDemo.CustomAjaxTextBox.initializeBase(this, [element]);
 
    //Initialize the private properties
    this._focusClass = null;
    this._blurClass = null;
}
 
//Define the prototype including properties and event handlers
CustomClientControlDemo.CustomAjaxTextBox.prototype = {
 
    //Define the get and set accessors for the properties.
    get_FocusClass: function () {
        return this._focusClass;
    },
    set_FocusClass: function (value) {
        this._focusClass = value;
    },
    get_BlurClass: function () {
        return this._blurClass;
    },
    set_BlurClass: function (value) {
        this._blurClass = value;
    },
 
    initialize: function () {
        var ajaxElement = this.get_element();
        //Call the base initialize
        CustomClientControlDemo.CustomAjaxTextBox.callBaseMethod(this, 'initialize');
 
        //Create handlers
        this._onFocusHandler = Function.createDelegate(this, this.onFocus);
        this._onBlurHandler = Function.createDelegate(this, this.onBlur);
 
        //AddHandlers
        $addHandlers(ajaxElement, { 'focus': this.onFocus, 'blur': this.onBlur }, this);
 
        //Set a default style for the control
        ajaxElement.className = this._blurClass;
    },
 
    onFocus: function (eventArgs) {
        this.get_element().className = this._focusClass;
    },
 
    onBlur: function (eventArgs) {
        this.get_element().className = this._blurClass;
    },
    dispose: function () {
        //Have the resource clean up code go in here.
    }
}
 
//Register the class deriving from Sys.UI.Control
CustomClientControlDemo.CustomAjaxTextBox.registerClass('CustomClientControlDemo.CustomAjaxTextBox', Sys.UI.Control);
 
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Using the AJAX Client Control on a Web Page

As we have created the client control’s code, in this section we will see about using it on a web page. Below are the high level steps in achieving it.

1. Add a web page to the sample web application that we created.

2. Add a ScriptManager control onto the webpage and add a ScriptReference to the CustomAjaxTextBox.js file.

3. Add an HTML text box to the form.

4. Use the $create script command to create the CustomTextBox control along with passing the required information like the setting the property values, etc., in the Sys.Application.add_init event handler.

Below is the web page code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AJAXClientControlDemo.aspx.cs"
    Inherits="WebApplication1.AJAXClientControlDemo" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        .Focus
        {
            background-color: Green;
            color: White;
        }
        .Blur
        {
            background-color: Black;
            color: White;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/CustomAjaxTextbox.js" />
        </Scripts>
    </asp:ScriptManager>
    <script type="text/javascript">
        Sys.Application.add_init(function (sender, args) {
            $create(CustomClientControlDemo.CustomAjaxTextBox, { FocusClass: 'Focus', BlurClass: 'Blur' }, null, null, $get('txtAjaxSample'));
        });
    </script>
    <div>
        <input type="text" id="txtAjaxSample" />
    </div>
    </form>
</body>
</html>

There is also an Asp.net Ajax custom control template available in Visual Studio 2010, which you can use to build the custom client controls. It will help you in building your control as a separate component, which can then be easily distributed across applications. This approach will involve some server side coding as well.

Happy reading!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read