Click here to Skip to main content
Click here to Skip to main content
Go to top

Auto complete text box using AJAX (Using Atlas)

, 1 Aug 2006
Rate this:
Please Sign up or sign in to vote.
How simple it is to have your own auto-complete text in ASP.NET 2.0.

Introduction

In this article, I will show how to build an auto complete text box from an ASP.NET TextBox control. With the help of Atlas, it's very easy to have your pages have AJAX abilities. Here is a screenshot of the final product:

Background: What is Atlas

"Atlas" is a free framework for building a new generation of richer, more interactive, highly personalized cross-browser web applications. This new web development technology from Microsoft integrates cross-browser client-script libraries with the ASP.NET 2.0 server-based development framework. In addition, "Atlas" offers you the same type of development platform for client-based web pages that ASP.NET offers for server-based pages. And because "Atlas" is an extension of ASP.NET, it is fully integrated with server-based services. "Atlas" makes it possible to easily take advantage of AJAX techniques on the web, and enables you to create ASP.NET pages with a rich, responsive UI and server communication. However, "Atlas" isn't just for ASP.NET. You can take advantage of the rich client framework to easily build client-centric web applications that integrate with any backend data provider and runs on most modern browsers.

Step 1 - Get your next website be ready for Atlas

System requirements

  • Supported Operating Systems: Windows Server 2003; Windows XP.

Required software

  • Microsoft .NET Framework version 2.0
  • IE 5.01 or later: You must also be running Microsoft Internet Explorer 5.01 or later for all installations of the .NET Framework.

Optional software

  • Visual Studio 2005 or Visual Web Developer Express Edition (free download).

Install "Atlas" Setup - June CTP. This setup application installs the core "Atlas" files on your machine, and installs a Visual Studio 2005 web site template for creating your own "Atlas" application from a blank "Atlas" web project. If you have IIS installed, the setup can configure it to recognize file extensions used by "Atlas". You can find the latest Atlas framework at http://atlas.asp.net/default.aspx?tabid=47&subtabid=471. View the step-by-step installation instructions here. Once you have Atlas installed, you are ready to rock!

Step 2 - Create a new "Atlas" Web site

  • Start Visual Studio.
  • On the File menu, click New Web Site (Alternatively, click New, and then click Web Site).
  • Under My Templates, select ASP.NET 'Atlas Web Site'.
  • Select the location for your installation, select the language you want to use for the Web site, and enter or browse to the local path where you want to create the Web site: click OK.

When you create a new "Atlas" Web site, Visual Studio copies the "Atlas" run-time assembly from its installation location to the Web site's Bin folder. Visual Studio also generates a Web.config file that is preconfigured with settings required to run "Atlas" applications.

Step 3 - Let's do some AJAX baby!

First, we start with a very simple ASP.NET HTML page:

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
         "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>

As you can see, there is not much to know in this code. All I have here is a simple server-side ASP.NET TextBox. Now the objective is to get this text box have AJAX abilities and make it an auto-complete text box. For that, I would need to add a ScriptManager Atlas control.

<atlas:ScriptManager ID="ScriptManager1" runat="server" />

The ScriptManager control is central to "Atlas". It manages all "Atlas" components in a page, handles partial page updates, and renders client scripts that enable you to access Web Service methods from JavaScript using proxy objects. The next thing we want to add under our TextBox control is our AutoCompleteExtender control from Atlas:

<atlas:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server">

<atlas:AutoCompleteProperties Enabled="true"
  MinimumPrefixLength="1"
  TargetControlID="TextBox1"
  ServicePath="~/Services/ProductService.asmx"
  ServiceMethod="FindProducts" />
</atlas:AutoCompleteExtender>

What is AutoCompleteExtender?

The AutoCompleteBehavior component extends text box controls with auto-completion behavior, which sends the text that the user has entered to a Web Service method to obtain a list of suggestions for completing the text. The result is displayed in a drop-down panel underneath the text box. The user can use either the mouse or the keyboard to select one of the suggested strings.

To extend a text box with auto complete behavior, create a Web Service containing a method with the following signature:

public string[] GetSuggestions(string prefixText, int count);

The prefixText parameter contains the text that the user has entered so far. The count parameter specifies the maximum number of possible values to return to the client. The method returns an array of strings that are displayed one to a line in the drop-down panel. No drop-down panel appears if the result is empty or if the Web Service does not return a result at all. The method name is determined by the ServiceMethod property, and can be any valid C# identifier. The parameter names must match the ones used in the method signature above. Once you have a Web Service that retrieves a list of suggestions, you can add an AutoCompleteBehavior component to the behaviors element of a TextBox control. At a minimum, you must set the serviceURL and serviceMethod properties, to specify the Web Service used to obtain suggestions. Several other properties exist, to fine-tune the behavior of auto-completion lists, including completionInterval to specify how frequently the suggestions get updated, completionSetCount to limit the number of suggestions returned, and minimumPrefixLength to set the minimum number of characters the user must enter before any suggestions are shown. After adding these two Atlas controls, our UI page should look like this:

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
              "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<atlas:ScriptManager ID="ScriptManager1" runat="server" />
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<atlas:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server">
<atlas:AutoCompleteProperties Enabled="true"
    MinimumPrefixLength="1"
    TargetControlID="TextBox1"
    ServicePath="~/Services/ProductService.asmx"
    ServiceMethod="FindProducts" />
</atlas:AutoCompleteExtender> 
</form>
</body>
</html>

Step 3 - Write our Data Layer

With the help of Microsoft Data Access Application Block for .NET, I created a very simple and useful data layer (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/daab.asp). Note: I have included all the code in the download sample. I have two classes:

  • sqlHelper - Microsoft Application Block for ADO.NET.
  • SqlProductProvider - our data provider, which has a method to return a SqlDataReader.

Here is our function from the SqlProductProvider class:

public static SqlDataReader GetProductLists(String owner)
{
    SqlDataReader reader = SqlHelper.ExecuteReader(ConnectionString, 
                               "GetProjectLists", owner);
    return reader;
}

Our Web Service will call this function, to get all the records that start with a given string (the string that you type in your text box). I know that this function will be called every time the user will push a key; therefore, I decided to call a Stored Procedure. Our Stored Procedure is very simple; it takes only one parameter and does a SQL Select with all the product names that start with that parameter:

SELECT
    ProductName
FROM
    Products
WHERE
    ProductName like @pProductName +'%'

Step 4 - Write our Web Service

Let's have a look at the code:

[WebMethod]
public String[] FindProducts(String prefixText, int count)
{
    //return all records whose Title starts with the prefix input string
    List<STRING> titleArList = new List<STRING>();

    SqlDataReader drProducts = sqlProductProvider.GetProductLists(prefixText);

    while (drProducts.Read())
    {
        String strTemp = Convert.ToString(drProducts["ProductName"]);
        titleArList.Add(strTemp);
    }
    return titleArList.ToArray();
}

The WebMethod FindProducts will be called each time the usee types in the text box, passing two values:

  • prefixText - the text typed
  • count - number of characters (for example, 2 characters for "IV")

In this function, I loop my dataReader and add the results to an array. And in the end, I return the array and that's all. Here is a screenshot that shows our auto-complete text box in action when you type the letter "c".

Summary

Let's review how all this works: we added an Atlas control called AutoCompleteExtender. This control talks to a Web Service containing a method with the following signature:

public string[] GetSuggestions(string prefixText, int count);

Each time the user types in the text box, this method will be triggered, passing the string the user typed and the number of characters. The next step is to write a query that runs with the given string and returns an array of strings:

SqlDataReader drProducts = sqlProductProvider.GetProductLists(prefixText);

while (drProducts.Read())
{
    String strTemp = Convert.ToString(drProducts["ProductName"]);
    titleArList.Add(strTemp);
}
return titleArList.ToArray();

Now the AutoCompleteExtender control does the rest; it generates the JavaScript code for the AJAX and links to the text box we want to do the auto-complete for. The great thing about all this is my text box is still an ASP Server control, so I still have all the power in the code-behind to do whatever I want with a rich UI.

Try my code

Here are the steps to run my code:

  1. Download the zip file.
  2. Copy the folder "AtlasTextBoxAutoComplete" to your web site folder (C:\Documents and Settings\[your name]\My Documents\Visual Studio 2005\WebSites).
  3. Open VS2005 and create a new C# web site called "AtlasTextBoxAutoComplete" (don't need to select the Atlas template since my site already has all the Atlas DLLs), and point the site to the location you saved your folder (C:\Documents and Settings\[your name]\My Documents\Visual Studio 2005\WebSites\AtlasTextBoxAutoComplete).
  4. VS2005 will give you a message saying "Web Site already exists". Now, you select "Open the existing web site", and push OK.
  5. Click on default.aspx (to make it your start up page) and run.
  6. Type the letter "c" and wait 3 seconds... and see the magic. (The look up is on the Product Table on Product Name.)

Feedback

Feel free to leave any feedback on this article; it's my first one, so go easy on me.

License

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

Share

About the Author

rperetz
Web Developer TrafficTech
Canada Canada
Have technical skills that can be demonstrated and an ability to resolve complex problems quickly while working in a demanding, high pressure environment
 
Designs, plans, and coordinates software development work teams
 
Provides technical mentorship to project team members
 
Handles complex application features and technical designs for the development of new applications.
 
Write articles about ASP.net:
http://www.codeproject.com/KB/aspnet/SQLHelper20.aspx http://www.codeproject.com/KB/aspnet/DateAndTimePicker.aspx http://www.codeproject.com/KB/aspnet/SQLHelper20.aspx http://www.codeproject.com/KB/aspnet/WaitImageBoxWhilePagePost.aspx
 
Designs and implements the components, frameworks and layers required for complex application features
 
Understands and participate in all aspects of the Software Development Life Cycle
 
Relies on experience and judgment to plan and accomplish goals.
 
Ability to perform various programming activities (coding, testing, debugging, documenting, maintaining and supporting).
 
Ability to work independently with minimal supervision.
 
10 years’ experience in web software design and development.
 
SpecialtiesASP.net
SQL 2005
AJAX 1.0
Linq
C# 3.5
Microsoft Application Blocks
Java Script
Reporting Services
SQL SSIS
XML
Classic ASP

Comments and Discussions

 
GeneralNeed ASP version of Auto complete script Pinmembermaddy4in20-Jun-10 0:47 
GeneralRe: Need ASP version of Auto complete script Pinmemberrperetz12-Aug-10 12:34 
GeneralRe: Need ASP version of Auto complete script Pinmemberrperetz20-May-11 3:47 
GeneralAjaxControlToolkit PinmemberMember 7816103-Sep-08 19:24 
GeneralRe: AjaxControlToolkit PinmemberTalha Ekram18-Mar-09 23:44 
GeneralRe: AjaxControlToolkit Pinmemberrperetz28-Jan-10 9:53 
GeneralAtals is old Pinmemberrperetz3-Sep-08 4:24 
Generalshould AutoCompleteExtender used only with webservice PinmemberMember 7816102-Sep-08 23:58 
GeneralRe: should AutoCompleteExtender used only with webservice Pinmemberrperetz3-Sep-08 4:24 
GeneralRe: should AutoCompleteExtender used only with webservice PinmemberMember 7816103-Sep-08 19:07 
QuestionGet the code Pinmemberkollam200328-Jul-08 2:02 
AnswerRe: Get the code Pinmemberrperetz3-Sep-08 4:25 
QuestionMultiple auto complete PinmemberShariful Islam24-Jul-08 0:20 
Questionauto suggest not working Pinmemberdhasu12310-Jun-08 9:03 
QuestionAutoComplete TextBox Pinmemberrafiq_22jmr28-May-08 2:07 
QuestionUsing page method instead of WEB SERVICE... PinmemberBobb198212-May-08 19:34 
QuestionHow to change datasource PinmemberKasmax31-Oct-07 2:23 
GeneralUsing AJAX PinmemberAdeel6883-Sep-07 1:42 
GeneralRe: Using AJAX Pinmemberrperetz12-Sep-07 3:29 
Questionissue with AutoCompleteExtender PinmemberRohit_Puranik26-Aug-07 20:40 
GeneralYour Lecture is Awesome, However I insist add 1 Line... Pinmembercoverboy10-Jul-07 3:50 
GeneralRe: Your Lecture is Awesome, However I insist add 1 Line... Pinmemberrperetz21-Aug-07 5:01 
QuestionModifying AutoCompleteExtender to pass more parameter Pinmemberbrnskm27-Jun-07 5:45 
AnswerRe: Modifying AutoCompleteExtender to pass more parameter PinmemberSaramMalik25-Jan-10 6:57 
GeneralRe: Modifying AutoCompleteExtender to pass more parameter Pinmemberrperetz26-Jan-10 17:01 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140921.1 | Last Updated 1 Aug 2006
Article Copyright 2006 by rperetz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid