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!



Related Articles

Comments

  • Custom Client Control

    Posted by shravan on 07/04/2012 11:17pm

    i am not getting any difference between html text box and ajax text box control how to use it and why to use please let me know.

    • reply

      Posted by V. N. S. Arun on 07/18/2012 10:03pm

      You can compare the ajax text box with a custom control on Asp.Net but the difference is that it has some customized features like changing the background on focus and on blur by making use of the Ajax script functions. The code provided in the article was just a simple example. You can build more sophisticated ajax client controls using this methodology.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Event Date: April 15, 2014 The ability to effectively set sales goals, assign quotas and territories, bring new people on board and quickly make adjustments to the sales force is often crucial to success--and to the field experience! But for sales operations leaders, managing the administrative processes, systems, data and various departments to get it all right can often be difficult, inefficient and manually intensive. Register for this webinar and learn how you can: Align sales goals, quotas and …

  • On-demand Event Event Date: July 22, 2014 In this WhatWorks analysis, John Pescatore examines a use case where end users had local administrative rights on their PCs and it had gotten out of hand for this Fortune 500 Energy and Utilities company. The compelling event that prompted the company to reexamine this situation was the migration to Windows 7. In Windows XP, a custom tool that allowed users one of three levels of administrative rights to their workstations would need to be replaced during the Windows …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds