Click here to Skip to main content
Click here to Skip to main content

Creating an ASP.NET AJAX Control Extender Using VS 2008

By , 5 Dec 2008
 

Introduction

ASP.NET AJAX Extender controls add features (usually AJAX or JavaScript support) to existing controls already declared on a page. With VS 2005, you had to manually wire-up control extenders yourself (either via source-view or via the property grid). This is not necessary with the newly released VS 2008, and can be done easily using the "Add Extender" feature. The following example demonstrates the addition of AJAX support to a TextBox in VS 2008.

Using the code

Step 1: Create a simple ASP.NET website using the VS 2008 templates by accepting defaults at a suitable location.

Step 2: Add a new project using File->Add->New Project->Visual C# -> ASP.NET AJAX Server Control Extender, as shown:

Step 3: Modify ExtenderControl1.cs as follows. Add the following attributes to the ExtenderControl1 class:

[
    TargetControlType(typeof(TextBox))
]

[
    DefaultProperty("Contacts"),
    ParseChildren(true, "Contacts"),
    ToolboxData(
      "<{0}:QuickContacts runat="\""server\"> </{0}:QuickContacts>")
]

Step 4: Add a property as follows to the ExtenderControl1 class:

private ArrayList contactsList;
[
Category("Behavior"),
Description("The contacts collection"),
DesignerSerializationVisibility(
    DesignerSerializationVisibility.Content),
Editor(typeof(ContactCollectionEditor), typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public ArrayList Contacts
{
    get
    {
        if (contactsList == null)
        {
            contactsList = new ArrayList();
        }
        return contactsList;
    }
}

Step 5: Modify the GetScriptDescriptors method as follows:

protected override IEnumerable<ScriptDescriptor>
              GetScriptDescriptors(System.Web.UI.Control targetControl)
{
    ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor(
          "AjaxTextWithTableExtender.ClientBehavior1",
          targetControl.ClientID);
    descriptor.AddProperty("contactsList", this.Contacts);
    return new ScriptBehaviorDescriptor[] { descriptor };

   // yield return descriptor;
}

Step 6: Modify the ClientBehavior1.initializeBase function by adding the following lines:

this.contactsList=null;
this.strtext=null;
this.flag=true;

Add the following lines to ClientBehavior1.prototype Initialize function. Note: ve careful with the commas.

$addHandler(this.get_element(), 'keyup',
        Function.createDelegate(this, this._onkeyup));
        this._onkeyup();

and also add the following:

get_contactsList : function() {
    return this.contactsList;
},
set_contactsList : function(value) {

    this.contactsList=value;
    this.raisePropertyChanged('contactsList');
},
_onkeyup : function() {
   this.strtext=document.getElementById("TextBox1").value;
  

var links = new Array ("link1", "link2", "link3"); 
var links_url = new Array ("link1.htm", "link2.htm",  
"link3.htm"); 

/* Resolve the location */ 
var loc=String(this.location); 

loc=loc.split("/"); 
loc=loc[loc.length-1].split("."); 
loc=loc[loc.length-2]; 

           
var v=new Array(this.contactsList);
//////////////////////////////////////////////////////////////////

var t = document.getElementById("TextBox1");
if (t) {
    // alert(this.flag);

    if(this.flag)
    {
        var mybody = document.getElementsByTagName("body")[0];
        // creates <table> and <tbody> elements
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < 1; j++) {
            // creates a <tr> element
            for(var i = 0; i < 2; i++) {
            // creates a <td> element

                mycurrent_row = document.createElement("tr");
                if(this.strtext!=null & v[0][i].Email.substring(0,1)!=null)
                {
                    //alert("strtext is not null");

                    if(v[0][i].Email.substring(0,1)==this.strtext.substring(0,1))
                    {
                        //alert("next shows v[0][i].
                        //       Email.substring\(0,1\)==this.strtext.substring\(0,1\)");
                        //alert(v[0][i].Email.substring(0,1)==this.strtext.substring(0,1));

                        mycurrent_cell = document.createElement("td");

                        //////////////////////////////////////////////////

                        linkEmail=document.createElement("a");
                        linkEmail.setAttribute("href",links_url[0]);
                        mycurrent_cell.appendChild(linkEmail);
                        var stre=v[0][i].Email;
                        //alert(str);  

                        currenttext = document.createTextNode(stre);
                        linkEmail.appendChild(currenttext);
                        // appends the cell <td> into the row <tr>
                        mycurrent_row.appendChild(mycurrent_cell);
                                
                        /////////////////////////////////////////////////////

                        mycurrent_cell = document.createElement("td");
                        // creates a Text Node

                        stre=v[0][i].Name;
                        //alert(str);  

                        currenttext = document.createTextNode(stre);
                        // appends the Text Node we created into the cell <td>

                        mycurrent_cell.appendChild(currenttext);
                        // appends the cell <td> into the row <tr>

                        mycurrent_row.appendChild(mycurrent_cell);
                         //////////////////////////////////////////////////   

                        mycurrent_cell = document.createElement("td");
                        // creates a Text Node
  
                           var stre=v[0][i].Phone;
                        //alert(str);  

                        currenttext = document.createTextNode(stre);
                        // appends the Text Node we created into the cell <td>

                        mycurrent_cell.appendChild(currenttext);
                        // appends the cell <td> into the row <tr>

                        mycurrent_row.appendChild(mycurrent_cell);
                        /////////////////////////////////////////////////////
                    }
                }
                mytablebody.appendChild(mycurrent_row);
            }
            // appends the row <tr> into <tbody>
        }

        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;

        mytable.setAttribute("border","2");
        if(this.strtext=='')
            this.flag=true;
        else
            this.flag=false;
        }
    }    
}

Step 7: The editor used to create the contacts collection is ContactCollectionEditor, which is based on the example found at: http://msdn2.microsoft.com/en-us/library/ms178654.aspx. Now compile the ExtenderControl project. Open the designer of your website's Default.aspx. You will find your ExtenderControl added at the top of the Toolbox. Now add a Label and a TextBox as shown:

Step 8: Click on the arrow to the right of the TextBox and choose "Add Extender". The following screen pops up:

Step 9: Select ExtenderControl1 and accept the default ID for the extender. If everything is fine, a "Remove Extender" option will appear below the "Add Extender" option for the TextBox. Right click the TextBox and in Properties, navigate to TextBox1_Extender. Add some dummy records to the Contacts collection with the following ContactCollectionEditor:

Step 10: Add an HTML file called "link1.htm" to your website project. Build the example and run the website.

Test the control

Add the letter 'a' or the first letter of one of the email records you entered, and watch the extender control work. It should be something like this:

The matching records from the Contacts collection are displayed and they can be linked as well.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

mitibhat
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Layout  Per page   
GeneralCustomer ExtenderControl in DataGrid or RepeatermemberNoFearUSA3 Feb '10 - 8:14 
I wrote a custom extender control by inheriting from my own base class that implements IExtenderControl. It works quite well except when I place it in a datagrid. I get the following Javascript error "Microsoft JScript runtime error: Sys.InvalidOperationException: Two components with the same id '{ExtenderControlId}' can't be added to the application." and the functionality only works for the control in the first row.
 
Can you please advise on a fix?
 
thank you
GeneralMy vote of 1memberDmitri Nesteruk5 Dec '08 - 10:26 
-
GeneralThe Scenario [modified]memberspolarium721 May '08 - 20:34 
First of all, thanks for the reply. I am currently in the process of studyng the code from AJAX Control Toolkit. I am looking for that Contacts Property you mentioned. Im hoping to somehow manipulate it...
 
Now, I have to explain how I came to this point.
 
I am consuming a web service that posts data asynchronously into an ASP.NET AJAX Page.
 
I wanted all error messages to come into my application just the way that the validator callout from the toolkit does. The behavior is the same but with this major difference --- If I use a validator control, it will only be checking if the data is valid. And not if the search returned no results. And or if I wanted some custom messages like 'This Billing is Overdue'.
 
So I decided to create my own Callout control extender.
I figured that it can have a Message property. And when the OnPrerender fires, I can check the length of that string. If it has 0 length, then nothing happens, but it it has content, then it shows the message in the callout box.
 
I just dont know how to do that.
 
modified on Thursday, May 22, 2008 9:58 PM

GeneralRegarding this Articlememberspolarium720 May '08 - 21:29 
Im trying to create my own AJAX Control Extender...
Its supposed to have a function much like the Validator Callout from the AJAX Control Toolkit but I want it to display messages from an asynchronous webservice event handler. And I dont have ideas as of how to do this yet. Could you point me to the right direction?
Generalnew Implementmemberkianoosh soorani15 Dec '07 - 3:43 
Can u implement the lookup with search for large data
with your article
GeneralRe: new Implementmembermitibhat17 Dec '07 - 21:54 
The property called Contacts is of the type ArrayList and is a public property. You could assign the data to this and use the search. I hope that answers your question.
Miti
GeneralRe: new Implementmembermitibhat17 Dec '07 - 21:56 
Of course you need to change the code a liitle i.e. for the table generation.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 5 Dec 2008
Article Copyright 2007 by mitibhat
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid