ASP.NET AJAX - Working with AutoCompleteExtender in the AJAX Toolkit

Introduction

Learning ASP.NET AJAX seems inevitable for most .NET developers, since it truly improves the user experience and also helps improve the performance of the web pages like partial page refreshes, calling services from the client side and so on.

In addition to the basic controls like UpdatePanel which are added to Microsoft Visual Studio by default, Microsoft also has released AJAXToolkit which is an out-of-the-box component. The AJAXControlKit has the extender AJAX controls which can be used as extenders for the existing ASP.NET controls in order to inject the ajaxified behavior on to them.

In this article we will be looking at an extender for the text box control called AutoCompleteExtender. You can download the latest releases of the AjaxToolKit from here.

AutoCompleteExtender control

The AutoCompleteExtender control is an extender for the ASP.NET TextBox control. This enables the list of items to be displayed in the sliding panel which slides down the bottom of the textbox based on the entered text in the textbox. It comes in handy when you want the users to know the items already exist in your application which they can choose or allow them to enter a new item which is not present in the list. The autocomplete extender control requires a webservice to expose a method to return the items based on the entered text. This service will be called by the extender control in the AJAX way.

Let us create a demo application and implement the autocomplete extender functionality.

Demo Application

Let us use ASP.NET 4.0 and Microsoft Visual Studio 2010 for developing the demo application. As a first step create a simple Website and name it as AjaxControlKitDemoWebsite.

Create a Webservice

The autocomplete extender requires a webservice which exposes a method returning a type string array and accepts prefix text, count or prefix text, count, contextkey as parameters.

Create a folder called Services under the website and add a webservice file with .asmx file, name it as DataService.asmx. Go to the server side code behind of the DataService.asmx file and add the below code.

[System.Web.Script.Services.ScriptService]
public class DataService : System.Web.Services.WebService {

    public static IList<string> _cityList;
    public DataService () {

    }

    [WebMethod]
    public string[] GetCities(string prefixText, int count) {

        //Gets the city list
        IList<string> cityList = GetCityData();

        //using linq to select the cities based on the prefix text
        var result = from city in cityList.AsEnumerable()
                     where city.ToUpper().StartsWith(prefixText.ToUpper())
                     select city;
        //return the result as a string[] by taking only the top n
        return result.Take(count).ToArray<string>();
    }

    private IList<string> GetCityData()
    {
        if (_cityList == null)
        {
            CreateCityList();
        }

        return _cityList;
    }

    private static void CreateCityList()
    {
        _cityList = new List<string>();
        _cityList.Add("Boston");
        _cityList.Add("NewYork");
        _cityList.Add("California");
        _cityList.Add("New Jersey");
        _cityList.Add("Denver");
        _cityList.Add("Detroit");
        _cityList.Add("Idaho");
        _cityList.Add("Ohio");
        _cityList.Add("Los Angeles");
        _cityList.Add("Las Vegas");
        _cityList.Add("Philadelphia");
        _cityList.Add("Phoenix");
        _cityList.Add("San Antonio");
        _cityList.Add("San Diego");
        _cityList.Add("Dallas");
        _cityList.Add("San Jose");
        _cityList.Add("San Francisco");
        _cityList.Add("Columbus");
        _cityList.Add("Seattle");
        _cityList.Add("Washington");
        _cityList.Add("Oklahoma City");
        _cityList.Add("New Orleans");
        _cityList.Add("Honolulu");
        _cityList.Add("Virginia Beach");
    }    
}

In the above code if you see there will be an attribute [System.Web.Script.Services.ScriptService] which will help the AJAX from the client side to invoke the web service. For the demo purpose I have created the method GetCities. Here is a small description:

  • Return Type - string[]
  • Parameters
    • prefixText - Text entered by the user in the textbox
    • maximum number of items returned

The parameter values will be passed by the extender control AJAX scripts while invoking the web service. You can also have another parameter of type string to which the context key specified in the extender control.



ASP.NET AJAX - Working with AutoCompleteExtender in the AJAX Toolkit

Create .aspx Page

Create a webform .aspx file and name it as AutoCompleteExtenderDemo. The first thing to create an AJAX page is to add a ScriptManager control onto the page, this will take care of adding the required AJAX libraries onto the page. So add the ScriptManager control under the form section of the page. Now drag drop a TextBox control. You can very well click on the Add Extender option on the smart tag displayed for the TextBox as shown in Fig 1.0 and select the AutoCompleteExtender from the list of extenders displayed as shown in Fig 1.1.

[app1.jpg]
Fig 1.0

[extender2.jpg]
Fig 1.1

Below shown is the SourceCode for textbox and autocomplete extender control on the .aspx page.

        <asp:TextBox ID="TextBoxCity" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender ID="TextBoxCity_AutoCompleteExtender" runat="server" 
            BehaviorID="AutoCompleteExtenderBehaviour"
            DelimiterCharacters="" 
            Enabled="True" 
            ServicePath="Services/DataService.asmx" 
            TargetControlID="TextBoxCity"
            ServiceMethod="GetCities"
            EnableCaching="true"
            ShowOnlyCurrentWordInCompletionListItem="true"
            CompletionSetCount="10"
            MinimumPrefixLength="1">
        </asp:AutoCompleteExtender>

You will notice that I have provided the values for some properties explicitly. Below is a brief description:

  1. ServicePath: Relative path of the webservice which we created earlier
  2. TargetControlId: To which TextBox the extender is created. In our case it is the CityTextBox.
  3. ServiceMethod: WebMethod exposed by the webservice which will be used for fetching the cities to be displayed based on the extered text.
  4. EnableCaching: Enables the caching on the selected items for the entered text. This improves the performance.
  5. CompletionSetCount: Maximum items to be displayed.
  6. MinimumPrefixLength: Minimum number of characters that the user has to type in for the item list to slide in.

Let us run the application. Fig 2.0 shows the output.

[output3.jpg]
Fig 2.0

[output4.jpg]
Fig 2.1

Hope you noticed how the list of cities is displayed when the user has typed the prefix text as "san" and the items are also selected and the selected item gets populated in the textbox as shown in Fig 2.1.

Add a Little Animation

You could also add a little animation to the auto complete extender by providing fade in and fade out when the slide panel does OnShow and OnHide. Below is the code:

<asp:TextBox ID="TextBoxCity" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="TextBoxCity_AutoCompleteExtender" runat="server" 
            BehaviorID="AutoCompleteExtenderBehaviour"
            DelimiterCharacters="" 
            Enabled="True" 
            ServicePath="Services/DataService.asmx" 
            TargetControlID="TextBoxCity"
            ServiceMethod="GetCities"
            EnableCaching="true"
            ShowOnlyCurrentWordInCompletionListItem="true"
            CompletionSetCount="10"
            MinimumPrefixLength="1">
           <Animations>
                <OnShow>
                    <Sequence>
                         <HideAction Visible="true"></HideAction>
                         <FadeIn Duration=".50" Fps="10"/>
                    </Sequence>
                </OnShow>
                <OnHide>
                    <Sequence>
                         <HideAction Visible="true"></HideAction>
                         <FadeOut Duration=".50" Fps="10"/>
                    </Sequence>
                </OnHide>
           </Animations>
</asp:AutoCompleteExtender>

Conclusion

I hope this article provided a good look at the implementation for the AutoComplete extender control of the AJAXToolKit. I have also attached the website for your reference.

Happy reading and see you in my next article!





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

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

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Best-in-Class organizations execute on a strategy that supports the multi-channel nature of customer requests. These leading organizations do not just open up their service infrastructures to accommodate new channels, but also empower their teams to deliver an effective and consistent experience regardless of the channel selected by the customer. This document will highlight the key business capabilities that support a Best-in-Class customer engagement strategy.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds