asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Adding Google Suggest Functionality to an ASP.NET Application
By Niraj Sharma
Rating: 3.8 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article



    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 explain 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 datasource for loading auto-suggest menu.

    1. Background
    2. What is AutoSuggestBox?
    3. Adding AutoSuggestBox to Your Web Application
    4. How Does it Work
    5. Conclusion

    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 selectiing 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 that 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 control for the purpose of selecting cities and airports. I thought that would be perfect for 'Travelope', too. And that was how AutoSuggestBox was born.

    What is AutoSuggestBox?

    AutoSuggestBox is a custom control written in C# that makes it simple to add 'Google Suggest'-like functionality to your web application. 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 look and feel of the control on the web page.

    Click here for the demo.

    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 auto-suggest menu.
    • GetAutoSuggestBox.aspx -- returns html that contains suggested items.

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

    More detailed instructions are here.

    Specify data types for loading auto-suggest menu items

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

    To add a data source you need to modify the 'GetAutoSuggestData.aspx' file. By default the class implements "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 suggested cities from the database according to characters typed by the user. It loads the top 10 cities starting with the specified keyword. Then it generates an array of ASBMenuItems and fills it with 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 LoadMenuItems function.

    Insert AutoSuggestBox control into a web form

    1. Create or open 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 at the location where you want suggest box to appear:

      <Custom:AutoSuggestBox id="Control ID" runat="server"
          DataType="Supported Data Type"
          CssClass="Text Box Style"
          MaxLength="Max chars in TextBox"
          Columns="Num of visible chars"
      />

      For example:

      <Custom:AutoSuggestBox id="asbCity" runat="server"
          DataType="City"
          CssClass="FormCtrlStyle"
          MaxLength="100"
          Columns="30"
      />

    4. Make sure that value of DataType attribute has been implemented in 'GetAutoSuggestData.aspx.cs' See previous section.

    5. If your web application doesn't run in the root of the webserver (ex. http://localhost/WebApp), then you need to add another attribute to autosuggestbox tag:

      <Custom:AutoSuggestBox id="asbCity" runat="server"
          DataType="City"
          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 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 suggest menu is visible - appropriate menu item is selected
      • If the user clicked 'enter' suggest menu becomes invisible, while the current selection is filled into the suggest box
    3. If the user typed an alphanumeric character, Javascript sends an XmlHttpRequest to GetAutoSuggestData page on the server
    4. The 'GetAutoSuggestData.aspx' page 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. It then uses the results of the query to create 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 application using the free AutoSuggestBox control.

    Happy programming!!!

    References

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

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 21, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 1
    While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
    [Read This Article]  [Top]
    Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
    With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
    [Read This Article]  [Top]
    Mar 10, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2, Cont'd
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 9, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 3, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1, Cont'd
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Mar 2, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Feb 16, 2005 - Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
    In ASP.NET 2.0 and Visual Studio 2005, you can quickly program custom authentication pages with the provided Membership Login controls. In this article, Dina Fleet Berry examines the steps involved in using the Login control with a custom SQL Server membership database.
    [Read This Article]  [Top]
    Dec 29, 2004 - ClickOnce Deployment in .NET Framework 2.0
    In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications.
    [Read This Article]  [Top]
    Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
    With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
    [Read This Article]  [Top]
    Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
    Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry