Google+ Peter Bromberg's .NET Blog | All posts tagged 'AUTOCOMPLETE'

Peter Bromberg's .NET Blog All Things Programming

Using the AJAX Autocomplete Extender With Multiple Values

18. May 2013 12:50 by admin in ASP.NET

The MS Ajax Autocomplete extender allows you to change a texbox into a typeahead dropdown list allowing you to select one of the matches to a search. Here is how it can be used to handle  both display text and value items with a bit of Javascript.

 

First let’s have a look at key elements of the markup:

<script type = "text/javascript">function clientItemSelected(sender, e) {
             $get("<%=hfZipcode.ClientID %>").value = e.get_value();
        }
    </script><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <asp:Label runat="server" ID="lblText" Text="Enter City Search string" />
        <asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender ID="AutoCompleteEx" runat="server"  TargetControlId="txtZip"
ServiceMethod="GetCompletionList"
              ServicePath="Default.aspx"
            MinimumPrefixLength="2" 
            CompletionInterval="1000"
            EnableCaching="true"
            CompletionSetCount="20" 
            CompletionListCssClass="autocomplete_completionListElement" 
            CompletionListItemCssClass="autocomplete_listItem" 
            CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
            DelimiterCharacters=";, :"
            OnClientItemSelected = "clientItemSelected" >
             <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 0px 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 0px and fade out --%>
                        <Parallel Duration=".4">
                            <FadeOut />
                            <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
                        </Parallel>
                    </OnHide>
                </Animations>
            </asp:AutoCompleteExtender> 
          <asp:HiddenField ID="hfZipcode" runat="server" />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            onclick="btnSubmit_Click" /> <asp:Label ID="lblMessage" runat ="server" />
    </form>

 

 
Here is the associated codebehind class for the page, which includes the Page Method that returns the requested data:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;namespace Autocomplete
{public partial class Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}[System.Web.Script.Services.ScriptMethod()][System.Web.Services.WebMethod]public static List<string> GetCompletionList(string prefixText, int count){using (SqlConnection conn = new SqlConnection()){conn.ConnectionString = 
            ConfigurationManager.ConnectionStrings["default"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {cmd.CommandType = CommandType.StoredProcedure;cmd.CommandText = "GetZipInfoByCityName";cmd.Parameters.AddWithValue("@SearchTerm", prefixText);cmd.Parameters.AddWithValue("@maxRecs", 20);cmd.Connection = conn;conn.Open();List<string> zips = new List<string>();using (SqlDataReader sdr = cmd.ExecuteReader()){while (sdr.Read()){string item = 
                 AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(sdr["CityState"].ToString(), 
                                   sdr["Zipcode"].ToString());zips.Add(item);}}conn.Close();return zips;}}}protected void btnSubmit_Click(object sender, EventArgs e){lblMessage.Text = "You selected " + hfZipcode.Value;}}
}

The trick for handling the value that gets submitted upon a selection is the little javascript clientItemSelected function. This is triggered by the OnClientItemSelected = "clientItemSelected" attribute of the Autocomplete extender. The downloadable code includes the SQL Server database files for a ZIP CODE database. Simply attach this database to your local copy of Sql Server and you should be ready to test it out.

 

Autocomplete.zip (3.33 mb)