Click here to Skip to main content
15,885,824 members
Articles / Web Development / HTML
Article

Auto Suggest Using AJAX.NET Library

Rate me:
Please Sign up or sign in to vote.
3.85/5 (6 votes)
14 Dec 20053 min read 70.3K   587   61   8
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.

C#
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.

C#
[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.

JavaScript
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.

JavaScript
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


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
General"AutoSuggest" undefined Pin
Member 44821378-Jun-10 0:03
Member 44821378-Jun-10 0:03 
GeneralHi Pin
jaime862-Apr-09 2:57
jaime862-Apr-09 2:57 
GeneralGreat work buddy Pin
Jagz W14-Nov-08 1:25
professionalJagz W14-Nov-08 1:25 
GeneralMicrosoft JScript runtime error: 'AutoSuggest' is undefined Pin
Gochi18-Apr-08 4:49
Gochi18-Apr-08 4:49 
GeneralRe: Microsoft JScript runtime error: 'AutoSuggest' is undefined Pin
Ana D.14-Aug-09 9:33
Ana D.14-Aug-09 9:33 
I'm having the same error. Were you able to solve it? If so, please, post how you solved it.
Thanks,
Ana
GeneralRe: Microsoft JScript runtime error: 'AutoSuggest' is undefined Pin
Tinhtam17-Feb-10 12:07
Tinhtam17-Feb-10 12:07 
Generalauto suggest box Pin
Siva Myneni2-May-07 1:39
Siva Myneni2-May-07 1:39 
Generalsome improvements.. Pin
weinboerse10-Mar-06 0:44
weinboerse10-Mar-06 0:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.