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

Auto Suggest Using AJAX.NET Library

, 14 Dec 2005
Rate this:
Please Sign up or sign in to vote.
This article is about improvisations on implementing the Google Suggest functionality using the AJAX.NET library.

Introduction

Sometime ago, I wrote an article in which I demonstrated how one can implement the Google Suggest functionality using the AJAX.NET library. This article takes one step forward and shows how to improve the functionality and select the suggestions using the arrow keys. The article is also supplemented with code which is provided at the end of the article.

Downloading the AJAX.NET Library

First of all, you need to download the AJAX.NET library created by Michael Schwarz. Now that you have downloaded the library and made the reference to the DLL in your project, we can start with some dirty stuff.

If you are not familiar on how to use the AJAX.NET library, than please visit my article AJAX In Action in which I explain in detail how to get started with the library.

Implementing the Server Side Methods

Let's start by implementing the server side methods. The server side methods will populate the collection with the data from the database. In this article, I am using the Northwind database which is installed as the default database for SQL Server 7 and SQL Server 2000 databases.

The first thing I will do is to get the data from the database. Let's see how this can be done.

private ArrayList PopulateArrayList()
{
    ArrayList categoryNameList = new ArrayList();
    string query = "SELECT CategoryName FROM Categories";
    SqlConnection myConnection = new SqlConnection(ConnectionString);
    SqlCommand myCommand = new SqlCommand(query, myConnection);
    SqlDataReader dr = null;

    try
    {
        myConnection.Open();
        dr = myCommand.ExecuteReader();

        while (dr.Read())
        {
            if (dr["CategoryName"] != null)
            {
                categoryNameList.Add((string)dr["CategoryName"]);
            }
        }
    }
    finally
    {
        dr.Close();
        myCommand.Dispose();
        myConnection.Close();
    }

    return categoryNameList;
}

The code above demonstrates how you can populate an ArrayList with the CategoryName column from the Northwind Categories table.

Now, let's see the Search method which searches the ArrayList for the word input by the user.

[Ajax.AjaxMethod]

public string Search(string searchString)
{
    string word = String.Empty;
    ArrayList wordList = new ArrayList();
    wordList = PopulateArrayList();

    /* You can put wordList in the Cache object
       to improve performance */

    foreach (string str in wordList)
    {
        if (str.ToLower().StartsWith(searchString.ToLower()) 
            && searchString != "")
            word += str + "<BR>";
    }

    return word;
}

The method that you want to call from the client side is marked with the [Ajax.AjaxMethod] attribute. First, I populate the ArrayList and then loop through the list to search for the word. Each time I find the word that starts with the same alphabet which the user has input, I concatenate the character to the word with the line break tag so that when they are displayed on the screen they are on different lines.

Client Side Methods

All the magic happens in the client side code. There are many client side methods and I will discuss some of the methods that are the most important. You can download the source code files which include the complete source code of the Auto-Suggest application. The method SearchWord shown below is the heart and soul of the application. In this method, I trap all the key-press events which include the Tab key event and the arrow-key events.

function SearchWord(pressevent,keyValue)
{
    var charCode = (pressevent.which)? pressevent.which : (event.keyCode);

    // alert(charCode);
    // Send to the Server Side Method to get the string
    if(charCode >=65 && charCode <=90 || 
       charCode >= 97 && charCode <=122) {
        AutoSuggest.Search(keyValue,SearchWord_CallBack);
    }

    // if the backspace key (8) is pressed and 48 is for the delete button
    else if(charCode == 8 || charCode == 48)
    {
        // Reset the count
        _highlightSuggestionIndex = -2;
        AutoSuggest.Search(keyValue,SearchWord_CallBack);
    }

    // when the down arrow key is pressed
    else if(charCode == 40)
    {
        if((_highlightSuggestionIndex+2) <= 
            document.getElementById("Display").childNodes.length)
        {
            _highlightSuggestionIndex = _highlightSuggestionIndex + 2;
        }

        Highlight(_highlightSuggestionIndex);
    }

    // When the up arrow key is pressed
    else if(charCode == 38)
    {
        if((_highlightSuggestionIndex-2) >= 0) {
            _highlightSuggestionIndex = _highlightSuggestionIndex -2;
        }
        Highlight(_highlightSuggestionIndex);
    }
}

Another important method is SearchWord_CallBack(response). This method gets the response back from the server side method named Search.

function SearchWord_CallBack(response)
{
    var word = response.value;

    if(response != null)
    {
        document.getElementById("Display").style.visibility = "visible";
        document.getElementById("Display").innerHTML = 
                    word.substring(0,word.length - 4);
    }
}

There are several other methods which add different functionality to the application. You can download the complete source code and view the code in detail.

One thing that I would like to see is to change the background color of the rows of the suggestion menu when the arrow keys are pressed. If you implement this functionality, shoot me an email at azamsharp_at_gmail.com and I will append it to this article.

I hope you like this article, happy coding!

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

Share

About the Author

azamsharp
Web Developer
United States United States
I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop

Comments and Discussions

 
General"AutoSuggest" undefined PinmemberMember 44821378-Jun-10 0:03 
GeneralHi Pinmemberjaime862-Apr-09 2:57 
GeneralGreat work buddy PinmemberNonu Walia14-Nov-08 1:25 
GeneralMicrosoft JScript runtime error: 'AutoSuggest' is undefined PinmemberGochi18-Apr-08 4:49 
GeneralRe: Microsoft JScript runtime error: 'AutoSuggest' is undefined PinmemberAna D.14-Aug-09 9:33 
GeneralRe: Microsoft JScript runtime error: 'AutoSuggest' is undefined PinmemberTinhtam17-Feb-10 12:07 
Generalauto suggest box PinmemberSiva Myneni2-May-07 1:39 
Generalsome improvements.. Pinmemberweinboerse10-Mar-06 0:44 

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
Web03 | 2.8.141015.1 | Last Updated 14 Dec 2005
Article Copyright 2005 by azamsharp
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid