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)
{
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 typedcount
- 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:
- Download the zip file.
- Copy the folder "AtlasTextBoxAutoComplete" to your web site folder (C:\Documents and Settings\[your name]\My Documents\Visual Studio 2005\WebSites).
- 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).
- VS2005 will give you a message saying "Web Site already exists". Now, you select "Open the existing web site", and push OK.
- Click on default.aspx (to make it your start up page) and run.
- 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.