WEBSITE

The ASP.NET AJAX Control Toolkit (part 3) - The AutoCompleteExtender

1/24/2011 5:28:46 PM

3. The AutoCompleteExtender

The Accordion is an example of a completely new control that has ASP.NET AJAX features baked in. Although this is a perfectly reasonable approach to integrating Ajax techniques with the web control model, it's not the most common solution that you'll see used in ASP.NET AJAX Control Toolkit. In fact, the ASP.NET AJAX Control Toolkit includes just a few new controls, and a much larger set of control extenders.

A control extender is a .NET component that adds features to an existing ASP.NET control. Control extenders allow you to use the same Ajax effects with countless different controls. This is useful when you're dealing with multipurpose features such as automatic completion, drag-and-drop, animation, resizing, collapsing, masked editing, and so on.

One of the many control extenders in the ASP.NET AJAX Control Toolkit is the AutoCompleteExtender, which allows you to show a list of suggestions while a user types in another control (such as a text box). Figure 3 shows the AutoCompleteExtender at work on an ordinary TextBox control. As the user types, the drop-down list offers suggestions. If the user clicks one of these items in the list, the corresponding text is copied to the text box.

Figure 3. Providing an autocomplete list of names

To create this example, you need an ordinary text box, like this:

Contact Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Next, you need to add the ScriptManager and an AutoCompleteExtender control that extends the text box with the autocomplete feature. The trick is that the list of suggestions needs to be retrieved from a specialized code routine called a web method, which you need to create in your page.

NOTE

You may have heard about web methods and web services, which are remotely callable code routines that can share data between different organizations, programming platforms, and operating systems. The web method you'll use with ASP.NET AJAX isn't quite as ambitious. Although it uses some of the same plumbing, it has a much simpler goal. It's really just a way for the text box to get a list of word suggestions without going through the whole page life cycle.

Here's an example of how you might define the AutoCompleteExtender. It uses the TargetControlID property to bind itself to the txtName text box, and it sets the MinimumPrefixLength property to 2, which means autocomplete suggestions won't be provided until the user has entered at least two characters of text. Finally, the ServiceMethod property indicates the web method you're going to use is named GetNames(). Before you can run this page, you need to create that method.

<asp:AutoCompleteExtender ID="autoComplete1" runat="server"
TargetControlID="txtName" ServiceMethod="GetNames" MinimumPrefixLength="2">
</asp:AutoCompleteExtender>


The next step is to create the GetNames() web method. Here's the basic method you need to add to the code-behind class of your web page:

<System.Web.Services.WebMethod> _
<System.Web.Script.Services.ScriptMethod> _
Public Shared Function GetNames(ByVal prefixText As String, _
ByVal count As Integer) As List(Of String)
...
End Function

The web method accepts two parameters, which indicate the text the user has typed so far and the desired number of matches (which is ten by default). It returns the list of suggestions. The two attributes that precede the GetNames() method indicate that it's a web method (meaning the client should be allowed to call it directly with HTTP requests) and that it supports JavaScript calls (which is what the AutoCompleteExtender uses).

Actually writing the code that retrieves or generates the suggestion list can be quite tedious. In this example, the code retrieves the list of name suggestions from the Northwind database. To ensure that this step is performed just once (rather than every single time the user hits a key in the text box):

Dim names As List(Of String)

' Check if the list is in the cache.
If HttpContext.Current.Cache("NameList") Is Nothing Then
' If not, regenerate the list. The ADO.NET code for this part
' isn't shown (but you can see it in the downloadable examples

names = GetNameListFromDB()

' Store the name list in the cache for sixty minutes.
HttpContext.Current.Cache.Insert("NameList", names, Nothing, _
DateTime.Now.AddMinutes(60), TimeSpan.Zero)
Else
' Get the name list out of the cache.
names = CType(HttpContext.Current.Cache("NameList"), List(Of String))
End If
...

With the list in hand, the next step is to cut down the list so it provides only the ten closest suggestions. In this example, the list is already sorted. This means you simply need to find the starting position—the first match that starts with the same letters as the prefix text. Here's the code that finds the first match:

...
Dim index As Integer = -1
For i As Integer = 0 To names.Count - 1
' Check if this is a suitable match.
If names(i).StartsWith(prefixText) Then
index = i
Exit For
End If
Next

' Give up if there isn't a match.
If index = −1 Then Return New List(Of String)()
...

The search code then begins at the index number position and moves through the list in an attempt to get ten matches. However, if it reaches the end of the list or finds a value that doesn't match the prefix, the search stops.

...
Dim wordList As New List(Of String)()
For i As Integer = index To (index + count - 1)
' Stop if the end of the list is reached.
If i >= names.Count Then Exit For

' Stop if the names stop matching.
If Not names(i).StartsWith(prefixText) Then Exit For

wordList.Add(names(i))
Next
...

Finally, all the matches that were found are returned:

...
Return wordList

You now have all the code you need to create the effect shown in Figure 25-9.

4. Getting More Controls

The Accordion and AutoCompleteExtender only scratch the surface of the ASP.NET AJAX Control Toolkit, which currently includes about 50 components. The easiest way to start experimenting with other controls is to surf to http://www.asp.net/ajaxlibrary/act_tutorials.ashx, where you'll find a reference that describes each control and lets you try it out online.

Table 1 highlights some of the more interesting control extenders that are currently available in the ASP.NET AJAX Control Toolkit, and Table 25-2 lists the controls.

Table 1. Control Extenders in the ASP.NET AJAX Control Toolkit
NameDescription
AlwaysVisibleControlExtenderThis extender keeps a control fixed in a specific position (such as the top-left corner of the web page) even as you scroll through the content in a page.
AnimationExtenderThis powerful and remarkably flexible extender allows you to add animated effects such as resizing, moving, fading, color changing, and many more, on their own or in combination.
AutoCompleteExtenderThis extender allows you to supply a list of suggested entries based on partial user input. The list of entries is generated by a web service method, as described in the previous section.
CalendarExtenderThis extender shows a pop-up calendar that can be attached to a text box for easier entry of dates. When the user chooses a date, it's inserted in the linked control.
CascadingDropDownThis extender lets you link drop-down lists without coding the solution by hand.
CollapsiblePanelExtenderThis extender lets you collapse and expand panels on your page. The rest of the page content reflows around them automatically.
ColorPickerExtenderThis extender shows a pop-up color picker that can be attached to a text box for easy color selection.
ConfirmButtonExtenderThis extender intercepts button clicks on a Button, LinkButton, or ImageButton control and displays a confirmation message. The click event is suppressed if the user chooses to cancel the operation in the confirmation dialog box.
DragPanelExtenderThis extender allows you to drag a panel around the page.
DropDownExtenderThis extender turns almost any control into a drop-down list when the mouse moves over it. For example, you can use the DropDownExtender in conjunction with an ordinary Label control. The user can then move the mouse over it, pick a different item from the list (thereby changing the text in the label), and then move the mouse away (allowing the label to revert to its ordinary appearance).
DropShadowExtenderThis extender adds a graphical drop shadow effect around a panel. The drop shadow can be partially transparent, and you can control the size and roundness of its corners.
DynamicPopulateExtenderThis simple extender replaces the contents of a control with the result of a web service method call.
FilteredTextBoxExtenderThis extender allows you to restrict certain characters from being entered in a text box (such as letters in a text box that contains numeric data). This is meant to supplement validation, not replace it, as malicious users could circumvent the filtering by tampering with the rendered page or disabling JavaScript in the browser.
HoverMenuExtenderThis extender allows content to pop up next to a control when the user hovers over it.
ListSearchExtenderThis extender allows the user to search for items in a ListBox or DropDownList by typing the first few letters of the item text. The control searches the items and jumps to the first match as the user types.
MaskedEditExtenderThis extender restricts the kind of input that can be entered in a text box using a mask. (A mask is a string that defines a pattern for fixed-length text, and supplies prompt characters to help the user enter the value. For example, a phone number mask might display (___) ___-____ in the text box. As the user types, the placeholders are replaced with the valid numeric characters, and nonnumeric characters are rejected.) You can use the MaskedEditExtender in conjunction with the MaskedEditValidator to make sure that the user can't circumvent the JavaScript code and enter an invalid value.
ModalPopupExtenderThis extender allows you to create the illusion of a modal dialog box by darkening the page, disabling controls, and showing a superimposed panel on top.
MultiHandleSliderExtenderThis extender transforms an ordinary TextBox control into a slider. However, this slider has features beyond the standard ASP.NET server-side equivalent. Most notably, it supports multiple thumbs that can be dragged independently along the slider track. This is useful when using a slider to indicate a range of values.
MutuallyExclusiveCheckBoxExtenderThis extender allows you to associate a "key" with multiple CheckBox controls. When the user clicks a check box that's extended in this way, any other check box with the same key will be unchecked automatically.
NumericUpDownExtenderThis extender attaches to a text box to provide configurable up and down arrow buttons (at the right side). These buttons increment the numeric or date value in the text box.
PagingBulletedListExtenderThis extender attaches to a BulletedList and gives it client-side paging capabilities so that it can split a long list into smaller sections.
PasswordStrengthThis extender attaches to a text box. As you type, it ranks the cryptographic strength of the text box value (the higher the ranking, the more difficult the password is to crack). It's meant to be used as a guideline for a password-creation box.
PopupControlExtenderThis extender provides pop-up content that can be displayed next to any control.
ResizableControlExtenderThis extender allows the user to resize a control with a configurable handle that appears in the bottom-right corner.
RoundedCornersExtenderThis extender rounds the corners of any control for a clean, professional look.
SliderExtenderThis extender converts a text box into a graphical slider that allows the user to choose a numeric value by dragging a thumb to a position on a track.
SlideShowExtenderThis extender attaches to an image and causes it to display a sequence of images. The images are supplied using a web service method, and the slide show can loop endlessly or use play, pause, previous, and next buttons that you create.
TextBoxWatermarkExtenderThis extender allows you to automatically change the background color and supply specific text when a TextBox control is empty. For example, your text box might include the text Enter Value in light gray writing on a pale blue background. This text disappears while the cursor is positioned in the text box or once you've entered a value.
ToggleButtonExtenderThis extender turns the ordinary ASP.NET CheckBox into an image check box.
UpdatePanelAnimationExtenderThis extender allows you to use the same animations as the AnimationExtender. However, it's designed to work with an UpdatePanel and perform these animations automatically when an update is in progress or once the panel has been refreshed.
ValidatorCalloutExtenderThis extender extends the client-side logic of the ASP.NET validation controls so that they use pop-up validation callouts that point to the control with the invalid input.

Table 25.2. Controls in the ASP.NET AJAX Control Toolkit
NameDescription
AccordionThis control stacks several content panels and allows you to view one at a time. When you click a panel, that panel is expanded and the other panels are collapsed (so that just the header is visible). Additional features include an automatic fading effect and an option to limit the size of the control (in which case large content regions use scrolling when visible).
AsyncFileUploadThis control is similar to the FileUpload web control, except it does its work asynchronously, allowing the user to continue interacting with the page. (Obviously, posting back the page or navigating to a new page will interrupt the asynchronous file transfer.) The AsyncFileUpload control can also be configured to show another control while the upload is taking place. Usually, this second control (which is referenced by the ThrobberID property) shows a simple animation so the user knows that an upload is underway.
ComboBoxThis control is inspired by the Windows combo box, which provides a drop-down list (like the ASP.NET DropDownList control) and allows the user to type in arbitrary text (like the ASP.NET TextBox control). It adopts much of the programing interface and most of the conventions of its Windows counterpart.
EditorThis remarkably powerful control provides HTML editing, complete with a toolbar of commands. The user can switch between three views: Html (which shows the markup), Design (which shows a correctly rendered preview, like a word processor), and Preview (which is similar to Design, but not editable).
NoBotThis control performs several checks to attempt to detect whether an automated program (a bot) is accessing the page rather than a human. If NoBot determines that a bot is accessing the page, the request will be denied. This technique is used to prevent programs that steal content or submit comment spam to blog postings, although it can obviously be circumvented. For example, NoBot forces the browser to perform a JavaScript calculation that uses the HTML DOM and submit the result, which aims to catch a non-browser application accessing the page. NoBot can also reject requests that post the form back extremely quickly, or post it back a large number of times in a specific time interval. Both behaviors suggest that an automated program is at work rather than a human.
RatingThis control allows users to set a rating by moving the mouse over a series of stars until the desired number of stars are highlighted.
ReorderListThis control creates a scrollable template list that allows the user to rearrange the order of items by dragging and dropping them.
SeadragonThis advanced control allows the user to zoom into a massively magifiable image. Behind the scenes, these images are composed out of a series of much smaller tiles, which are managed on the web server. To create a Seadragon image, you need the free Deep Zoom Composer tool (http://tinyurl.com/26wjeqt). It's also worth noting that these zoomable images are a much hyped feature that's built into Silverlight.
TabContainerThis control resembles the tabs shown in a Windows. Each tab has a header, and the user moves from one tab to another by clicking the header.

Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8
Visit movie_stars's profile on Pinterest.