Home / AJAX

HOW TO Use the AutoComplete Control

RSS
Modified on 2010/01/18 05:36 by Mike Pope Categorized as Uncategorized

AutoComplete Demonstration







Select a Movie:





You selected:

AutoComplete Description

AutoComplete extends any ASP.NET TextBox control. It associates that control with a popup panel to display words that begin with the prefix that is entered into the text box. When the user has entered more characters than a specified minimum length, a popup displays words or phrases that start with that value. By default, the list of words is positioned at the bottom left side of the text box.

The candidate words that match the user input are supplied by a Web service. Caching is enabled, so if the same characters are entered multiple times, only one call is made to the Web service.

Video - How Do I: Use the ASP.NET AJAX AutoComplete Control



AutoComplete Client Code Sample

<%@ Page Language="C#" %>
<script runat="server">
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static string[] GetSuggestions(string prefixText) {
        return new string[] {
            prefixText + "abc",
            prefixText + "def",
            prefixText + "ghi",
            prefixText + "jkl",
            prefixText + "mno"
        };
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <style type="text/css"> </style> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script> <script src="http://ajax.microsoft.com/ajax/beta/0911/Start.debug.js" type="text/javascript"></script> <script src="http://ajax.microsoft.com/ajax/beta/0911/extended/ExtendedControls.debug.js" type="text/javascript"></script> </head> <body> <form id="form1" runat="server"> <asp:AjaxScriptManager ID="sm1" runat="server" EnablePageMethods="true" /> <script type="text/javascript"> Sys.debug = true; Sys.require(Sys.components.autoComplete, function() { $("#tb1").autoComplete({ minimumPrefixLength: 1, serviceMethod: "GetSuggestions", servicePath: location.pathname }); }); </script> <div>

<input id="tb1" type="text" style="width:200px;"/> </div> </form> </body> </html>


AutoComplete Client Reference

Sys.Extended.UI.AutoCompleteBehavior Class

Events

  • populating - Adds or removes an event handler for the populating event.
  • populated(handler) - Adds or removes an event handler for the populated event.
    • Parameters - A function that represents the event handler.
  • showing(handler) - Adds or removes an event handler for the showing event.
    • Parameters - A function that represents the event handler.
  • shown(handler) - Adds or removes an event handler for the shown event.
    • Parameters - A function that represents the event handler.
  • hiding(handler) - Adds or removes an event handler for the hiding event.
    • Parameters - A function that represents the event handler.
  • hidden(handler) - Adds or removes an event handler for the hidden event.
    • Parameters - A function that represents the event handler.
  • itemSelected(handler) - Adds or removes an event handler for the itemSelected event.
    • Parameters - A function that represents the event handler.
  • itemOver(handler) - Adds or removes an event handler for the itemOver event.
    • Parameters - A function that represents the event handler.
  • itemOut(handler) - Adds or removes an event handler for the itemOut event.
    • Parameters - A function that represents the event handler.

Methods

  • initialize() - Initializes the autocomplete behavior.
  • dipose() - Disposes the autocomplete behavior.
  • initializeTimer(timer) - Initializes the timer.
    • Parameters - A Sys.UI.Timer object.
  • initializeTextBox(element) - Initializes the autocomplete text box.
    • Parameters - A Sys.UI.DomElement object.
  • initializeCompletionList(element) - Initializes the autocomplete list element.
    • Parameters - A Sys.UI.DomElement object.
  • showPopup() - Displays the completion-list popup.
    • Remarks - If you cancel the showing event, you should still call showPopup to ensure consistency of the internal state.
  • hidePopup() - Hides the completion-list popup.
    • Remarks - If you cancel the hiding event, you should still call hidePopup to ensure consistency of the internal state.
  • onShow() - Plays the OnShow animation.
  • onHide() - Plays the OnHide animation.
  • raisePopulating(eventArgs) - Raises the populating event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the populating event.
  • raisePopulated(eventArgs) - Raises the populated event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the populated event.
  • raiseShowing(eventArgs) - Raises the showing event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the showing event.
  • raiseShown(eventArgs) - Raises the shown event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the shown event.
  • raiseHiding(eventArgs) - Raises the hiding event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the hiding event.
  • raiseHidden(eventArgs) - Raises the hidden event.
    • Parameters - A Sys.EventArgs object that represents event arguments for the hidden event.
  • raiseItemSelected(eventArgs) - Raises the itemSelected event.
    • Parameters - A Sys.Extended.UI.AutoCompleteItemEventArgs object that represents event arguments for the itemSelected event.
  • raiseItemOver(eventArgs) - Raises the itemOver event.
    • Parameters - A Sys.Extended.UI.AutoCompleteItemEventArgs object that represents event arguments for the itemOver event.
  • raiseItemOver(eventArgs) - Raises the itemOut event.
    • Parameters - A Sys.Extended.UI.AutoCompleteItemEventArgs object that represents event arguments for the itemOut event.

Properties

  • isMultiWord - Gets a Boolean value that specifies whether the behavior is currently in multi-word mode.
  • onShow - Gets or sets a string that contains the JSON definition of the generic OnShow animation.
  • onShowBehavior - Gets a Sys.Extended.UI.Animation.GenericAnimationBehavior object that represents the behavior of the generic OnShow animation.
  • onHide - Gets or sets a string that contains the JSON definition of the generic hide animation.
  • onHideBehavior - Gets a Sys.Extended.UI.Animation.GenericAnimationBehavior object that represents the behavior of the generic OnHide nimation.
  • completionInterval - Gets or sets an integer that specifies the autocompletion timer interval, in milliseconds.
  • completionList - Gets or sets a Sys.UI.DomElement that represents the DOM element for the list.
  • completionSetCount - Gets or sets an integer that contains the maximum size of the completion set.
  • minimumPrefixLength - Gets or sets an integer that specifies the minimum length, in characters, of the text prefix that must be entered before a call is made to the Web service.
  • serviceMethod - Gets or sets the Web service method name.
  • servicePath - Gets or sets the Web service URL.
  • contextKey - Gets or sets a string that represents a user-specific or page-specific context that is passed to an optional overload of the Web method that is specified in the serviceMethod and servicePath properties.
    • Remarks - If the context key is used, it should have the same signature but must include an additional parameter named contextKey of type string.
  • useContextKey - Gets or sets a Boolean value that specifies whether the contextKey property should be used.
    • Remarks - The userContextKey property is automatically enabled if the contextKey property is set on either the client or the server. If the context key is used, it should have the same signature but must include an additional parameter named contextKey of type string.
  • enableCaching - Gets or sets a Boolean value that specifies whether autocomplete suggestions that are retrieved from the Web service should be cached.
  • completionListElementID - Gets or sets a string that contains the ID of the completion div element.
  • completionListCssClass - Gets or sets the CSS class name that is used to style the completion list element.
  • completionListItemCssClass - Gets or sets the CSS class name that is used to style an item in the completion list.
  • highlightedItemCssClass - Gets or sets a string that specifies the CSS class name that is used to style a highlighted item in the list.
  • delimiterCharacters - Gets or sets the character or characters that are used to seperate words for autocompletion.
  • firstRowSelected - Gets or sets a Boolean value that specifies whether the first option in the list is selected.
  • showOnlyCurrentWordInCompletionListItem - Gets or sets a Boolean value that specifies whether to show only the current word in the completion list item.
    • Remarks - If delimiter characters are specified and showOnlyCurrentWordInCompletionListItem is set to true, the completion list displays suggestions just for the current word. Otherwise, it displays the complete string that will be displayed in the text box if that item is selected.

Sys.Extended.UI.AutoCompleteItemEventArgs Class

  • Summary - Defines arguments for the itemSelected event.
  • Parameters - Sys.UI.DomElement item, String text, String value

Properties

  • item - Gets or sets the Sys.UI.DomElement item.
  • text - Gets or sets the text of the item.
  • value - Gets or sets the value of the item.
    • Remarks - This value can be different from the text if it is specifically returned by the Web service as an autocomplete JSON text/value item (using AutoComplete.CreateAutoCompleteItem); otherwise, it is the same as the text.

AutoComplete Sever Code Sample

        <div class="demoheading">AutoComplete Demonstration</div>
            Enter some characters into the text box.  The Web service returns random words
            that start with the text that you have entered.
            <br /><br />
            <p />
            <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
            <ajaxToolkit:AutoCompleteExtender
                runat="server" 
                BehaviorID="AutoCompleteEx"
                ID="autoComplete1" 
                TargetControlID="myTextBox"
                ServicePath="AutoComplete.asmx" 
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="2" 
                CompletionInterval="1000"
                EnableCaching="true"
                CompletionSetCount="20"
                CompletionListCssClass="autocomplete_completionListElement" 
                CompletionListItemCssClass="autocomplete_listItem" 
                CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
                DelimiterCharacters=";, :"
                ShowOnlyCurrentWordInCompletionListItem="true" >
                <Animations>
                    <OnShow>
                        <Sequence>
                            <%-- Make the completion list transparent and then show it --%>
                            <OpacityAction Opacity="0" />
                            <HideAction Visible="true" />
                            
                            <%--Cache the original size of the completion list the first time
                                the animation is played and then set it to zero --%>
                            <ScriptAction Script="
                                // Cache the size and setup the initial size
                                var behavior = $find('AutoCompleteEx');
                                if (!behavior._height) {
                                    var target = behavior.get_completionList();
                                    behavior._height = target.offsetHeight - 2;
                                    target.style.height = '0px';
                                }" />
                            
                            <%-- Expand from 0 px to the appropriate size while fading in --%>
                            <Parallel Duration=".4">
                                <FadeIn />
                                <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
                            </Parallel>
                        </Sequence>
                    </OnShow>
                    <OnHide>
                        <%-- Collapse down to 0 px and fade out --%>
                        <Parallel Duration=".4">
                            <FadeOut />
                            <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
                        </Parallel>
                    </OnHide>
                </Animations>
            </ajaxToolkit:AutoCompleteExtender>

<script type="text/javascript"> // Work around browser behavior of "auto-submitting" simple forms var frm = document.getElementById("aspnetForm"); if (frm) { frm.onsubmit = function() { return false; }; } </script> <%-- Prevent enter in textbox from causing the collapsible panel from operating --%> <input type="submit" style="display:none;" />

AutoComplete Server Reference

The properties in italics are optional.

<ajaxToolkit:AutoCompleteExtender 
    runat="server" 
    ID="autoComplete1" 
    TargetControlID="myTextBox"
    ServiceMethod="GetCompletionList"
    ServicePath="AutoComplete.asmx"
    MinimumPrefixLength="2" 
    CompletionInterval="1000"
    EnableCaching="true"
    CompletionSetCount="20" 
    CompletionListCssClass="autocomplete_completionListElement" 
    CompletionListItemCssClass="autocomplete_listItem" 
    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
    DelimiterCharacters=";, :"
    ShowOnlyCurrentWordInCompletionListItem="true">
        <Animations>
            <OnShow> ... </OnShow>
            <OnHide> ... </OnHide>
        </Animations>
</ajaxToolkit:AutoCompleteExtender>


  • TargetControlID - The ID of the control to extend.
  • ServiceMethod - The Web service method to call. The signature of this method must match the following:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(string prefixText, int count) { ... }

You can give the method any name, but the return type and parameter names and types must match exactly, including case.
  • ServicePath - The path of the Web service that the extender gets the word completion list from. If this is not provided, the method should be a method marked as a page method in the current page.
  • ContextKey - User-specific or page-specific context that is provided to an optional overload of the Web method that is specified by the ServiceMethod and ServicePath properties. If the context key is used, it should have the same signature but must include an additional parameter named contextKey of type string, as shown in the following example:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(
    string prefixText, int count, string contextKey) { ... }

You can replace GetCompletionList with any name, but the return type and parameter names and types must exactly match, including case.
  • UseContextKey - A Boolean value that specifies whether the contextKey property should be used. This will be automatically enabled if the ContextKey property is set on either the client or the server. If the context key is used, it should have the same signature but must have an additional parameter named contextKey of type string.
  • MinimumPrefixLength - An integer that specifies the minimum length of the text prefix that must be entered before a call is made to the Web service.
  • CompletionInterval - An integer that specifies the autocompletion timer interval in milliseconds.
  • EnableCaching - A Boolean value that specifies whether autocomplete suggestions that are retrieved from the Web service should be cached.
  • CompletionSetCount - An integer that contains the maximum size of the completion set.
  • CompletionListCssClass - The name of the CSS class that is used to style the completion list element.
  • CompletionListItemCssClass - The name of the CSS class that is used to style an item in the completion list.
  • CompletionListHighlightedItemCssClass - The name of the CSS class that is used to style a highlighted item in the list.
  • DelimiterCharacters - The delimiter (one or more characters) that is used to separate words. The text in the autocomplete textbox is tokenized using this delimiter and the Web service completes the last token.
  • FirstRowSelected - A Boolean value that determines whether the first option in the list is selected.
  • ShowOnlyCurrentWordInCompletionListItem - A Boolean value that specifies whether to show only the current word in the completion list item. If this property is true and a value is specified for the DelimiterCharacters property, the autocomplete list items display suggestions for the current word to complete and do not display the rest of the tokens.
  • Animations - Specifies the generic animation for the autocomplete extender. For more information, see Using Animations and Animation Reference.
  • OnShow - The animation to play each time the completion list is displayed. The completion list will be positioned correctly but hidden. The animation can include <HideAction Visible="true" /> to display the completion list along with any other visual effects.
  • OnHide - The animation to play each time the completion list is hidden.



AutoComplete Additional Code Samples

You can create a WCF service that works with the AutoComplete control by creating an AJAX-Enabled WCF Service in Visual Studio.

Image



The WCF service in the following code listing has a method named GetSuggestions. This method accepts a prefix parameter that represents the text that has been entered into the input element so far and a count parameter that represents the number of suggestions to return.

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Imports System.Collections.Generic
Imports System.Linq

<ServiceBehavior(IncludeExceptionDetailInFaults:=True)> _ <ServiceContract(Namespace:="")> _ <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _ Public Class MovieService

Private _movies As New List(Of String)

Public Sub New() _movies.Add("Star Wars") _movies.Add("Superman") _movies.Add("Matrix") _movies.Add("Matrix Reloaded") _movies.Add("Matrix Revolutions") _movies.Add("Kill Bill Volume 1") _movies.Add("Kill Bill Volume 2") End Sub

<OperationContract()> _ Public Function GetSuggestions(ByVal prefixText As String, ByVal count As Integer) As String() Dim matches = From m In _movies _ Where m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) _ Order By m _ Take count Return matches.ToArray() End Function

End Class

This service returns a list of movie suggestions. The suggestions are hard-coded. Alternatively, you could returns suggestions from a database table.

Image

  Name Size
- AutoComplete.png 25.44 KB
- CreateWCF.JPG 53.11 KB