Click here to Skip to main content
Click here to Skip to main content

Adding 'Google Suggest' functionality to an ASP.NET application

, 1 Dec 2005
Rate this:
Please Sign up or sign in to vote.
Shows how to add 'Google Suggest' functionality to an ASP.NET application.
Prize winner in Competition "ASP.NET Nov 2005"

Introduction

The purpose of this article is to show how to use the free AutoSuggestBox control to add 'Google Suggest' functionality to your ASP.NET application. There are plenty of articles available on the internet that explains how to do it, but there is usually just a lot of theory and not much code that you can easily add to your application. AutoSuggestBox encapsulates all the complex functionality and only requires developers to specify the data source for loading the auto-suggest menu.

Background

Have you seen Google Suggest? It is an application created by Google that demonstrates the power of AJAX. It is really amazing to see it for the first time, but in a little while, the notoriety wears off and most developers forget about it. While many people acknowledge its 'coolness' factor, they don’t know how to integrate it with other web applications.

The first time I saw this control, I came away with the same feeling. What an awesome idea, but I have no use for it. Several months ago, I started working on a travel application called 'Travelope' (see here). When working on the airfare search form, I was thinking of a simple interface for selecting FROM and TO locations. I considered using a combo box, but there were 1000s of cities, so the form would take a long time to load. Another option would be to use a text box with a link to popup a city lookup window. That would require users to open a reference window every time they forgot the spelling, so that would not be a great option either. I started looking at other travel sites for ideas. Many of these sites were using 'Google Suggest'-like controls for the purpose of selecting cities and airports. I thought that would be perfect for 'Travelope', too. And that was how AutoSuggestBox was born.

Using the code

What is AutoSuggestBox?

AutoSuggestBox is a custom control written in C# that makes it simple to add 'Google Suggest'-like functionality to your web applications. It supports C# and VB.NET and works in Internet Explorer as well as in Firefox. This control utilizes AJAX to retrieve data without refreshing the whole page. Developers can use CSS to adjust the look and feel of the control on the web page.

Adding AutoSuggestBox to your Web Application

Download the appropriate AutoSuggestBox package from here. There are four files that you need to add to your application to use AutoSuggestBox.

  • AutoSuggestBox.dll -- contains the control.
  • AutoSuggestBox.js -- JavaScript methods for AJAX support.
  • AutoSuggestBox.css -- look and feel of the auto-suggest menu.
  • GetAutoSuggestBox.aspx -- returns the HTML that contains the suggested items.

First, add a reference to 'AutoSuggestBox.dll'. Then create a sub-directory 'asb-includes' under the root of your web application. Copy the other three files into the new sub-directory.

More detailed instructions are available here.

Specify data types for loading auto-suggest menu items

When the user starts typing in the AutoSuggestBox, you need to provide a data source for the suggested values. The system allows for as many data sources as required by your application. For example, you can have one data source for the 'City' suggest box, another for the 'Airport'.

To add a data source, you need to modify the 'GetAutoSuggestData.aspx' file. By default, the class implements the "City" datasource. "LoadMenuItems" contains a switch statement for loading different types of data:

private ArrayList LoadMenuItems(string sDataType, string sKeyword) 
{
    ArrayList aMenuItems;

    switch(sDataType)
    {
        case "City":
            aMenuItems=LoadCities(sKeyword);
            break;
        default:
            throw new Exception("GetAutoSuggestData  Type '" + 
                      sDataType + "' is not supported.");
    }
    return aMenuItems;
}

The 'LoadCities' method retrieves the suggested cities from the database according to the characters typed in by the user. It loads the top 10 cities starting with a specified keyword. Then it generates an array of ASBMenuItems and fills it with the results from the database.

private ArrayList LoadCities(string sKeyword)
{
    ArrayList aOut=new ArrayList();

    string sConnString="Provider=Microsoft.Jet.OLEDB.4.0;" + 
           "Data Source=c:\\databases\\AutoSuggestBox_Demo.mdb;" + 
           "User Id=admin;Password=;";
    OleDbConnection oCn=new OleDbConnection(sConnString);

    string sSql="SELECT TOP 10 tblCity.Name as CityName, " +
                "tblCity.Code as CityCode, " +
                "tblCountry.Name as CountryName, " +
                "tblState.Name as StateName " + 
                " FROM (tblCity INNER JOIN tblCountry" + 
                " ON tblCity.CountryID=tblCountry.ID) " +
                " LEFT OUTER JOIN tblState" + 
                " ON tblCity.StateID=tblState.ID " + 
                " WHERE (tblCity.Name LIKE '" + 
                sKeyword.Replace("'", "''") + "%') " +
                " ORDER BY tblCity.Name";

    OleDbCommand oCmd = new OleDbCommand(sSql, oCn);
    oCn.Open();

    OleDbDataReader oReader = oCmd.ExecuteReader();

    string sCity;
    string sCityCode;
    string sState;
    string sCountry;
    
    string sLabel;

    ASBMenuItem oMenuItem;

    while (oReader.Read())
    {
        //Build label using City, Country & State
        sCity        =oReader.GetString(0);
        sCityCode    =oReader.GetString(1);
        sCountry    =oReader.GetString(2);

        if (oReader.GetValue(3)==System.DBNull.Value)
            sState="";
        else
            sState=oReader.GetString(3);
        

        sLabel=sCity;
        
        //Append either state or country
        if (sState != "")
            sLabel+=", " + sState;
        else
            sLabel+=", " + sCountry;
        
        oMenuItem=new ASBMenuItem();
        oMenuItem.Label=sLabel;
        oMenuItem.Value=sCityCode;
        
        aOut.Add(oMenuItem);
    } 

    oReader.Close();
    oCn.Close();

    return aOut;
}

If you need to add other data sources, just add more case statements to the LoadMenuItems function.

Insert the AutoSuggestBox control into a web form

  1. Create or open an already existing web form.
  2. Add the following line to the top of your ASPX page:
    <%@ Register TagPrefix="Custom" Namespace="ASB" Assembly="AutoSuggestBox" %>
  3. Add the following line to the location where you want the suggest box to appear:
    <Custom:AutoSuggestBox id="Control ID" 
             DataType="Supported Data Type" runat="server" 
             CssClass="Text Box Style" 
             MaxLength="Max chars in TextBox" 
             Columns="Num of visible chars"/>

    For example:

    <Custom:AutoSuggestBox id="asbCity" DataType="City" 
                runat="server" CssClass="FormCtrlStyle" 
                MaxLength="100" Columns="30"/>
  4. Make sure that value of the DataType attribute has been implemented in 'GetAutoSuggestData.aspx.cs'. See the previous section.
  5. If your web application doesn't run in the root of the webserver (e.g. http://localhost/WebApp), then you need to add another attribute to the AutoSuggestBox tag:
    <Custom:AutoSuggestBox id="asbCity" 
             DataType="City" runat="server" CssClass="FormCtrlStyle" 
             MaxLength="100" Columns="30" 
             ResourcesDir="/WebApp/AutoSuggestBox"/>

    Note: By default, the ResourcesDir is "/asb_includes".

How Does it Work

When the user starts typing text in the control, JavaScript handles the OnKeyUp, OnKeyDown and OnKeyPress events. Then, AJAX is used to contact the server side with every click, to retrieve a list of suggested entries.

So the flow of events is as follows:

  1. The user presses a key while the focus is on the AutoSuggestBox control.
  2. JavaScript checks if the user entered up/down/enter or any other character.
    • If the user entered up/down and the suggest menu is visible - the appropriate menu item is selected.
    • If the user clicked 'enter', the suggest menu becomes invisible, while the current selection is filled into the suggest box.
  3. If the user typed an alphanumeric character, JavaScript sends the XmlHttpRequest to the GetAutoSuggestData page on the server.
  4. The page 'GetAutoSuggestData.aspx' takes the current value of the text box and the type of data to retrieve. It usually generates a query to retrieve suggested values from the database. Then it uses the results of the query to create the HTML for the suggest menu and returns it back to the page.
  5. The web page retrieves the updated 'Suggest Menu' and displays it in place of the old one.

Conclusion

In this article, we demonstrated how simple it is to add 'Google Suggest' functionality to your web applications using the free AutoSuggestBox control.

Happy programming!!!

Points of Interest

  • Travelope -- a travel engine that implements the AutoSuggestBox.
  • AutoSuggestBox site -- contains all the info, demos and downloads related to the AutoSuggestBox control.
  • Google Suggest -- the site that started it all.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Niraj Sharma

United States United States
No Biography provided

Comments and Discussions

 
QuestionPut a full code sample Pinmemberchascos695-Mar-13 11:58 
AnswerRe: Put a full code sample PinmemberMorganSimon20-Mar-13 9:25 
GeneralReally good PinmemberMember 969771218-Dec-12 23:06 
QuestionHow can I add an attribute to the Anthem:AutoSuggestBox? Pinmembergoknikhil4-May-10 19:15 
GeneralMy vote of 2 PinmemberIndrajeet Sutar12-Apr-10 2:21 
Questionmaking the items appear on top infornt of other controls Pinmembersvknair26-Jun-09 21:04 
Generalnot working... PinmemberMember 397189116-Dec-08 19:52 
GeneralThis is really good Pinmemberdarlasrikanth27-Nov-08 22:01 
QuestionWould this work... Pinmemberdswett11-Mar-08 12:46 
AnswerRe: Would this work... Pinmembergamerdrew5-Aug-08 9:08 
QuestionDynamically adding Autosuggest Text Box problem! Pinmembergiger20-Nov-07 1:24 
I have a problem adding this control dynamically to my page
 
AutoSuggestBox txt = new AutoSuggestBox();
txt.MaxLength = 5;
txt.ResourcesDir="/FolderName/asb_includes";
txt.DataType="some_data_type";
txt.Width= new Unit(72,UnitType.Pixel);
txt.Attributes.Add("runat", "server");
txt.ID = someID;
rw.Cells[1].Controls.Add(txt);
 

It renders ok, but when I try to type in something I get this box pops up 4-5 times:
---------------------
A Runtime error has occured.
Do you wish to Debug?
 
Line: 2
Error: 'undefined' is null or not an object
---------------------
 
I have no idea why this happens. Is it possible to add this control the way I'm doing?
GeneralParser error Pinmemberjebin k24-Sep-07 19:51 
GeneralRe: Parser error Pinmemberdiadem_2k25-Sep-07 11:53 
GeneralRe: Parser error Pinmemberdiadem_2k25-Sep-07 12:03 
Questionpopup menu PinmemberAdawi9-Sep-07 20:30 
GeneralJavascript is Not Firing Pinmembersunny10capri22-Jun-07 12:49 
Questionworks fine on localhost but a problem on web server Pinmembergs_dhaliwal22-Jan-07 0:32 
QuestionJavascript Error - Object Expected [modified] PinmemberParakkat14-Nov-06 21:53 
AnswerRe: Javascript Error - Object Expected Pinmembergabbu103018-May-07 0:51 
GeneralAdded THe suggest box to my site but using atlas Pinmembervik201-Oct-06 17:25 
GeneralPressing Space to bring all 10 suggestions PinmemberH.Riazi14-Sep-06 23:59 
GeneralSource is currenty down... PinmemberKirk Severtson27-Aug-06 6:19 
GeneralRe: Source is currenty down... PinmemberNiraj Sharma28-Aug-06 5:24 
QuestionHTTPS [modified] PinmemberBerto Vermeer5-Jul-06 23:02 
GeneralOpera Pinmembertetak@monogram.sk4-Jul-06 22:47 
GeneralConcerning AutoSuggestBox.dll Pinmemberaspdotnet_22-Jul-06 23:12 
GeneralRe: Concerning AutoSuggestBox.dll Pinmembertex859622-Nov-06 18:22 
GeneralVery Nice - Thanks PinmemberAndy Hollis8-Jun-06 22:49 
GeneralDisable CSS Pinmemberdarwinc7-May-06 22:20 
QuestionHow to customize it to del.icio.us suggestion box style Pinmemberqiuyl5-Apr-06 20:16 
AnswerRe: How to customize it to del.icio.us suggestion box style PinmemberNiraj Sharma8-Apr-06 13:49 
GeneralRe: How to customize it to del.icio.us suggestion box style Pinmemberqiuyl8-Apr-06 16:04 
GeneralEnlarge the box Pinmembervzuniga5-Apr-06 15:41 
GeneralRe: Enlarge the box PinmemberNiraj Sharma8-Apr-06 13:43 
GeneralJavascript is Not Firing PinmemberPreethi Ramasamy23-Mar-06 7:50 
GeneralRe: Javascript is Not Firing PinmemberNiraj Sharma8-Apr-06 13:41 
QuestionBUG:TextChanged event? Pinmemberjim_kanepele27-Feb-06 22:43 
GeneralThis doesnt work Pinmemberrajamanan7-Feb-06 5:44 
GeneralRe: This doesnt work PinmemberNiraj Sharma7-Feb-06 7:49 
QuestionCan this be implemented on Normal Windows Application? Pinmemberconankunkid31-Jan-06 17:26 
AnswerRe: Can this be implemented on Normal Windows Application? Pinmembernsimeonov3-Mar-06 22:17 
GeneralTop job Pinmemberchitty225-Jan-06 23:34 
GeneralGreat Idea! PinmemberPaolo Gios12-Jan-06 22:48 
QuestionInput Text Limited to 5 chars? Pinmembernaeem_s31-Dec-05 23:09 
AnswerRe: Input Text Limited to 5 chars? PinmemberNiraj Sharma7-Feb-06 7:46 
QuestionCaching Pinmemberrippo8-Dec-05 23:17 
GeneralNice Job Done PinmemberAwaisAhmedKhan8-Dec-05 0:02 
Generalnice, but vulnerable... Pinmemberkb@Orvis7-Dec-05 2:31 
GeneralRe: nice, but vulnerable... PinmemberNiraj Sharma8-Dec-05 8:43 
GeneralRe: nice, but vulnerable... Pinmemberkb@Orvis8-Dec-05 13:32 

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
Web02 | 2.8.140721.1 | Last Updated 1 Dec 2005
Article Copyright 2005 by Niraj Sharma
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid