Google Suggest is way cool. You type your search text and it gets the hits without doing the POSTBACK. You can easily implement this functionality using AJAX. In this article we will create a very small application that works like Google suggest. I have just implemented the basic features and you are free to enhance it in any way.
Introduction:
Google Suggest is way cool. You type your search text and it gets the hits without doing the POSTBACK. You can easily implement this functionality using AJAX. In this article we will create a very small application that works like Google suggest. I have just implemented the basic features and you are free to enhance it in any way.
The implementation:
Let's first see a simple screen shot so that we will have better idea what we are talking about.
See, when I type "A" all the names starting with "A" pops up. Now let's see how this is done.
First we need to implement the server side methods that will get the data from the database. Here is the GetDataSet method that gets the DataSet filled with data from the database.
private DataSet GetDataSet()
{ DataSet ds = null; string query = @"SELECT * FROM tblPerson"; SqlConnection myConnection = new SqlConnection(GetConnectionString()); SqlDataAdapter ad = new SqlDataAdapter(query,myConnection); ds = new DataSet(); ad.Fill(ds,"tblPerson"); return ds; } |
Now that we have got the DataSet method done. Let's make a method that will be called from the JavaScript.
[Ajax.AjaxMethod]
public string FillList(string s) { string word = null; DataSet ds = new DataSet(); ds = GetDataSet(); ArrayList wordsList = new ArrayList(); foreach(DataRow dr in ds.Tables[0].Rows) { wordsList.Add(dr["Name"] as String); } foreach(string str in wordsList) { if( str.StartsWith(s) && s!=null) { word += str + "<BR>"; }}return word; } |
Now let's see the JavaScript code. First we made the TextBox as the HTML input control.
<input id="MyTextBox" type="text" onkeypress="GetWords(event,this.value)"> |
Now, we need to implement the GetWords method. The GetWords method takes two parameters one if the event and other is the TextBox value. If the character pressed in the input box is a "space" (using spacebar) than the text is displayed in the textbox depending on the selecting which is displayed in the DIV element.
<script language="javascript"> |
That's it. Now many of you will be wondering that why did I call GetDataSet again and again on every keypress event. I know it's extremely bad for performance. A good idea is to use Cache but unfortunately you cannot use Cache object for the methods that are being called from a method marked with [Ajax.Method] attribute. However you can use the ViewState object but be careful don't store too much information in the ViewState object.
For more information about why Cache cannot be implemented when a call is being made from Ajax marked method please visit my Blog entry Remote Scripting Caching Problems (AJAX).
I hope you liked the article, happy coding!