Home > Articles > Web Development > ASP.NET

Adding Client Capabilities to Server Controls Using the ASP.NET AJAX Control Toolkit

  • Print
  • + Share This
Learn how to use the AJAX Control Toolkit, which provides a much richer environment for creating extender controls than using the ASP.NET 2.0 AJAX Extensions alone. In addition, the toolkit includes myriad controls you can either use or build on, making the toolkit a compelling alternative.
This chapter is from the book

IN THE PRECEDING CHAPTER, we covered the architecture of the AJAX Control Toolkit, describing at a high level what it has to offer and the attributes, classes, and interfaces that make it all happen. The enhanced functionality you get in the toolkit, from attribute-based programming to rich animations, provides a compelling alternative to coding against the ASP.NET 2.0 AJAX Extensions and the Microsoft AJAX Library directly. In this chapter, we delve into the details of the toolkit a little further as we develop as series of extender controls that demonstrate the rich features the toolkit provides.

Adding Client-Side Behavior Using the ExtenderControlBase

The ASP.NET AJAX Control Toolkit provides many features to assist in the development of extender controls, such as the automatic creation of $create statements, the use of attributes to decorate extender control properties that should be included in the $create statement creation, built-in designer support, and many more. In this section, we revisit the ImageRotator extender we created in Chapter 5, "Adding Client Capabilities to Server Controls," and re-create it using the ASP.NET AJAX Control Toolkit. This approach enables us to compare the alternatives as we build the new extender.

The process of building an extender control using the ASP.NET AJAX Control Toolkit consists of four main steps.

  1. Create the template classes.
  2. Provide implementation for the inherited extender control class.
  3. Provide implementation for the Sys.UI.BehaviorBase-based JavaScript class.
  4. Attach the extender control to an existing server control.

Visual Studio 2008 Extender Control Library Template

The ASP.NET AJAX Control Toolkit comes with full support for Visual Studio 2008 in the form of a project template that is geared toward creating an extender control library project. The template, shown in Figure 11.1, creates a library project structure (see Figure 11.2) that contains an extender control class, a designer class, and a JavaScript behavior class. In this section, we look at the ImageRotatorExtender.cs, ImageRotatorDesigner.cs, and ImageRotatorBehavior.js files that the template generated for us as we begin to discuss creating a new and improved ImageRotator extender.

Figure 11.1

Figure 11.1 Extender control project template

Figure 11.2

Figure 11.2 Extender control project template structure

The ImageRotatorExtender class shown in Listing 11.1 serves as the basis for our ImageRotator extender control. The class inherits from ExtenderControlBase and provides a template that contains most of the required entries for us, such as the web resource registration of our associated behavior class, class attributes that associate the designer for the extender, the client script to be downloaded, and the target type for the extender. The template also creates a default property, demonstrating the use of the ExtenderControlProperty and DefaultValue attributes and the use of the GetPropertyValue method inside the property setter and getter.

Listing 11.1. ImageRotatorExtender Class

[assembly: System.Web.UI.WebResource(
"ImageRotator.ImageRotatorBehavior.js","text/javascript")]
namespace ImageRotator
{
  [Designer(typeof(ImageRotatorDesigner))]
  [ClientScriptResource("ImageRotator.ImageRotatorBehavior",
    "ImageRotator.ImageRotatorBehavior.js")]
  [TargetControlType(typeof(Control))]
  public class ImageRotatorExtender : ExtenderControlBase
  {
    [ExtenderControlProperty]
    [DefaultValue("")]
    public string MyProperty
    {
      get
      {
        return GetPropertyValue("MyProperty", "");
      }
      set
      {
        SetPropertyValue("MyProperty", value);
      }
    }
  }
}

The ImageRotatorDesigner class shown in Listing 11.2 will be the designer class for our ImageRotator extender control. The designer class provides default designer functionality for our extender control during design time. We associate the designer with our ImageRotatorExtender class by using the Designer attribute, which is automatically added when we use the template. The ExtenderControlBaseDesigner<T> class that the ImageRotatorDesigner class inherits from makes it possible for the properties of our extender control to show up in the Properties window while the design-time focus is on the image control we are extending. This default behavior provides a more efficient way of working with extenders and the controls they are extending.

Listing 11.2. ImageRotatorDesigner Class

namespace ImageRotator
{
  class ImageRotatorDesigner : AjaxControlToolkit.Design.
    ExtenderControlBaseDesigner<ImageRotatorExtender>
  {
  }
}

The ImageRotatorBehavior class shown in Listing 11.3 will be the client-side behavior class for our ImageRotator extender control. The class consists of the same structure we used in Chapter 5, but now inherits from the AjaxControlToolkit.BehaviorBase class, which provides added functionality for working with client state and interacting with the asynchronous request events of the Sys.WebForms.PageRequestManager.

Listing 11.3. ImageRotatorBehavior Class

/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />
/// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js"
    assembly="AjaxControlToolkit" />

Type.registerNamespace('ImageRotator');

ImageRotator.ImageRotatorBehavior = function(element) {
  ImageRotator.ImageRotatorBehavior.initializeBase(this, [element]);
  // TODO : (Step 1) Add your property variables here
  this._myPropertyValue = null;
}

ImageRotator.ImageRotatorBehavior.prototype = {
  initialize : function() {
    ImageRotator.ImageRotatorBehavior.callBaseMethod(this,'initialize');
    // TODO: Add your initialization code here
  },

  dispose : function() {
    // TODO: Add your cleanup code here
    ImageRotator.ImageRotatorBehavior.callBaseMethod(this, 'dispose');
  },

  // TODO: (Step 2) Add your property accessors here
  get_MyProperty : function() {
    return this._myPropertyValue;
  },
  set_MyProperty : function(value) {
    this._myPropertyValue = value;
  }
}

ImageRotator.ImageRotatorBehavior.registerClass(
  'ImageRotator.ImageRotatorBehavior', AjaxControlToolkit.BehaviorBase);

Inheriting from the ExtenderControlBase Class

The ASP.NET AJAX Control Toolkit comes with its own version of the System.Web.UI.ExtenderControl class, which provides additional functionality that supports the development pattern the toolkit is designed to work with. The AjaxControlToolkit.ExtenderControlBase class provides the inheritor support for serialization of property values, support for working with the toolkit-based attributes, seamless integration with control-based view state, support for working with client state, and the ability to specify an alternate script path for debugging and working with themes. The ImageRotatorExtender class in Listing 11.4 shows a much different-looking class than we saw in Chapter 5. The class no longer requires overrides for the GetScriptDescriptors and GetScriptReferences methods, it has class-level attributes, it has property-level attributes, and the property setters and getters are referencing their values through a method. So, let's go over these changes and see how we develop an extender control building on the structure the template provided for us.

The setting of the assembly-based WebResource attribute in our extender class is a pattern that all the extenders and script controls in the toolkit follow. This pattern helps centralize all the pieces for the component in one location instead of having to add an entry to the assembly when a new control is added to the toolkit. The attributes applied to the class that we cover in this section are the Designer, ClientScriptResource, RequiredScript, and TargetControlType attributes. The Designer attribute is used to specify the class that will provide design-time services to our extender. The ClientScriptResource attribute is used to include the client-side scripts for our extender and consists of the resource type and the full resource name and should refer to an embedded resource. The RequiredScriptResource attribute brings in the timer script file that is associated with the TimerScript class that we will use in our behavior class. Finally, the TargetControlType attribute is used to limit the types of controls our extender can be associated with.

The RotationInterval and ImageList properties of our class have also changed with the use of attributes and the reliance on the GetPropertyValue<T> and SetPropertyValue<T> methods to access our property data. The ExtenderControlProperty attribute is used to indicate that the property should be added to the ScriptComponentDescriptor as a property and later included in the $create statement that creates the behavior class on the client. The ClientPropertyName attribute is used to change the name of the property that is used when the property is added to the ScriptComponentDescriptor from the default value of the property name to the name provided to the attribute. The DefaultValue attribute, which comes from the System.CompnentModel namespace, is used to indicate to designers and code generators the default value of the property. The ExtenderControlBase class provides the GetPropertyValue<T> and GetPropertyValue<T> generic methods that get and set the property value directly from the control view state. By using these methods in our property setters and getters, a consumer of our extender can work with it in the designer, declaratively in the HTML editor, or in code and be assured that during a postback the values will be available.

Listing 11.4. ImageRotatorExtender Class

[assembly:System.Web.UI.WebResource("ImageRotator.ImageRotatorBehavior.js",
"text/javascript")]
namespace ImageRotator
{
  [ParseChildren(true, "ImageList")]
  [Designer(typeof(ImageRotatorDesigner))]
  [ClientScriptResource("ImageRotator.ImageRotatorBehavior",
     "ImageRotator.ImageRotatorBehavior.js")]
  [RequiredScript(typeof(TimerScript))]
  [TargetControlType(typeof(Image))]
  public class ImageRotatorExtender : ExtenderControlBase
  {
    [ExtenderControlProperty]
    [ClientPropertyName("rotationInterval")]
    [DefaultValue(3), DisplayName("RotationInterval(seconds))")]
    [DesignerSerializationVisibility(
      DesignerSerializationVisibility.Visible)]
    public int RotationInterval
    {
      get { return GetPropertyValue<int>("RotationInterval", 3); }
      set { SetPropertyValue<int>("RotationInterval", value); }
    }

    private ImageUrlList _imageList;
    [ExtenderControlProperty]
    [ClientPropertyName("imageList")]
    [DesignerSerializationVisibility(
      DesignerSerializationVisibility.Content)]
    [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
    public ImageUrlList ImageList
    {
      get
      {
        if (_imageList == null)
        {
            _imageList = GetPropertyValue<ImageUrlList>(
             "ImageList", null);
            if (_imageList == null)
            {
               _imageList = new ImageUrlList();
               SetPropertyValue<ImageUrlList>(
                "ImageList", _imageList);
            }
        }
        return _imageList;
      }
    }
  }
}

Creating the AjaxControlToolkit.BehaviorBase Class

The ASP.NET AJAX Control Toolkit comes with its own version of the Sys.UI.Behavior class, which provides additional functionality and supports the development pattern the toolkit is designed to work with. The AjaxControlToolkit.BehaviorBase class provides inheritor support for working with client state and interacting with the asynchronous request events of the Sys.WebForms.PageRequestManager. The support for working with client state is provided by the get_ClientState and set_ClientState methods that can be used to work with the string-based hidden field associated with your extender. The class also provides two methods tied to the beginRequest and endRequest events of the PageRequestManager, which can be overridden to provide specific functionality in your behavior in situations where an UpdatePanel is being used.

The ImageRotatorBehavior class shown in Listing 11.5 inherits from the BehaviorBase class and provides the client-side behavior for our extender control. The structure of this class is exactly the same as in Chapter 5, with the rotationInterval property used to set the interval at which the images will be swapped out and the imageList property containing an array of the images. The one change to the class is in the use of the Sys.Timer class, which is part of the ASP.NET AJAX Control Toolkit. This class, which is contained in the Compat/Timer folder, wraps the window.setInterval call, providing a cleaner interface for this timer-specific functionality. The Sys.Timer class is just one of many that come with the toolkit that provide added functionality to the existing Microsoft AJAX Library. If you look in the Compat and Common folders in the toolkit library project, you will find classes for working with dates, drag and drop, and threading, just to name a few.

Listing 11.5. ImageRotator Behavior Class

Type.registerNamespace('ImageRotator');

ImageRotator.ImageRotatorBehavior = function(element) {
  ImageRotator.ImageRotatorBehavior.initializeBase(this, [element]);

  this._imageIndex = 0;
  this._imageList = new Array();
  this._rotationInterval = null;
  this._timer = null;
}
ImageRotator.ImageRotatorBehavior.prototype = {
  initialize : function() {
    ImageRotator.ImageRotatorBehavior.callBaseMethod(this,
      'initialize');

    var element = this.get_element();

    if(this._imageList)
    {
      this._imageList =
        Sys.Serialization.JavaScriptSerializer.deserialize(
          this._imageList);
      this._imageList[this._imageList.length] = element.src;
    }

    if(this._rotationInterval == null)
      this._rotationInterval = 3;

      if(this._timer == null)
        this._timer = new Sys.Timer();

      this._timer.set_interval(this._rotationInterval * 1000);
      this._timer.add_tick(Function.createDelegate(this,
        this._rotateImage));
      this._timer.set_enabled(true);
  },

  dispose : function() {
    ImageRotator.ImageRotatorBehavior.callBaseMethod(this, 'dispose');
    if (this._timer)
    {
      this._timer.dispose();
      this._timer = null;
    }

    this._imageList = null;

  },
  get_rotationInterval: function(){
    return this._rotationInterval;
  },
  set_rotationInterval: function(value){
    this._rotationInterval = value;
  },
  get_imageList: function(){
    return this._imageList;
  },
  set_imageList: function(value){
    this._imageList = value;
  },
  _rotateImage: function(){
    var element = this.get_element();
    if(element)
    {
      element.src = this._imageList[this._imageIndex++];
      if(this._imageIndex > this._imageList.length - 1)
        this._imageIndex = 0;
    }
  }
}
ImageRotator.ImageRotatorBehavior.registerClass(
  'ImageRotator.ImageRotatorBehavior', AjaxControlToolkit.BehaviorBase);

Attaching the Extender to a Control

You can attach the ImageRotator extender to an image control by using the new Extender Control Wizard (see Figure 11.3) that comes with Visual Studio 2008 and thus provide the same design-time experience we saw in Chapter 5. The wizard is available from the smart tag of the image control by selecting the Add Extender option, which opens the wizard. The wizard enables the user to select an extender control from a list and associate it with a control. In our case, we would select the ImageRotator extender to associate it with the image control. After we do that, we add values to the RotationInterval property and ImageList property using the Properties window of the image control.

Figure 11.3

Figure 11.3 Extender Control Wizard

Final Thoughts

If we compare our experience of creating extender controls using the ASP.NET AJAX Control Toolkit to using the classes provided by the ASP.NET 2.0 AJAX Extensions, we can see that our development experience is much simpler. The use of attributes to register our properties to be included in the $create statements and to register our associated script files dramatically reduces the complexity of our code compared to implementing logic in the GetScriptDescriptors and GetScriptReferences methods. This convenience alone makes it worth using the toolkit, but if we tack on the added design-time features, support for working with client state, and the numerous added JavaScript files such as the Sys.Timer class, the reasons to switch get greater. The use of the toolkit can be compared to the use of the ActiveX Template Library (ATL) that was used to create ActiveX controls in C++. The template provided a ton of base classes and Visual Studio templates that made creating them a lot easier.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020