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

  • When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

  • U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date