Developing AutoComplete Textbox using ASP.NET AJAX 1.0, Web Service and JavaScript
 
Published: 26 Nov 2007
Abstract
This article explains how we can create a Textbox with AutoComplete feature using ASP.NET 2.0 Microsoft AJAX 1.0, Web Services and Javascript. We will see how we can expose a web service so that it can be invoked from a client side Javascript call.
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: 
Views (Total / Last 10 Days): 62947/ 44

Introduction

Invoking a web service method from JavaScript code (client side) is the essence of this article. Due to the introduction of AJAX 1.0 extension for ASP.NET 2.0 invoking a web service method from client side can be implemented with less lines of code. We can perform a variety of tasks combining AJAX and Web Service. One of the techniques is to create an AutoComplete Textbox using AJAX. To begin with, let us see how we can expose a web service method that can be invoked from a client side JavaScript code.

Outline

As a user types into the Textbox, a client side call is made to the web service; this in turn returns the possible word that matches the typed-in text. The Textbox is udpated with the word received from the Web Service. This is achieved without refreshing the web page. The call between the client and web service happens in such a fast manner that the user will not be aware that we are indeed making a call to the server when they type in.

Steps

The complete steps required to build an AutoComplete Textbox control are elaborated below.

Exposing a Web Service method to be invoked from Client Side

The following is a partial code snippet for a web service class definition.

Listing 1

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myServices : System.Web.Services.WebService {

In order to expose the class, "myServices" to be invoked from a client side, all we have to do is insert the following attribute above the class definition.

Listing 2

[System.Web.Script.Services.ScriptService()]

By adding the above line, the AJAX run time extensions will know that we are going to invoke the methods in the myServices class which is going to be invoked from the client side.

Now the methods defined in the myServices class web service are ready to be invoked from the client side. Let us pay some attention to how we can invoke the methods from client side using AJAX.

Invoking the web service method using AJAX

Any AJAX enabled web page should at least have one ScriptManager tag. One of the collections for this ScriptManager tag is the Services collection. Through this Services collection, we can refer to the asmx file that we are going to invoke. Now allow me to show the syntax for the Services collection.

Listing 3

<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Services>
    <asp:ServiceReference Path="myServices.asmx" />
  </Services>
</asp:ScriptManager>

Using the above code, we can invoke the methods defined in the myServices.asmx from client side.

JavaScript code to invoke a Web Service method

Listing 4

ret = className.methodName(Parameter1, OnComplete, OnError, OnTimeOut);

The above is the syntax to invoke a Web Service method from client side JavaScript code. Parameter1 is the parameter for the method. OnComplete, OnError and OnTimeOut are client side JavaScript function names. For example, the client side function "OnComplete" will be invoked once the asynchronous call to the web service method completes successfully. The function "OnError" will be invoked if the asynchronous call to the method results in any error. And finally, the client side function "OnTimeOut" will be invoked, if the asynchronous call to the method does not complete after a certain timeout. These three functions are user defined functions. So, you can name them to your wish. These functions will look as follows:

Listing 5

function OnComplete(arg) 
{
  alert (arg);
}
 
function OnTimeOut(arg) 
{
  alert("TimeOut encountered");
}
 
function OnError(arg) 
{
  alert("Error : " + arg);
}

How does an AutoComplete Textbox works?

Now, using the above technique, let us see how we can implement an AutoComplete Textbox. To begin with, the web service method should receive a parameter. This parameter will be the textbox content that the user will be typing in. The web method can compare against a dictionary of words that matches with the passed in parameter. When I say dictionary, it can be an ArrayList or a database call to get the list of matching words. This can be implemented according to your business logic. For our discussion we will use an ArrayList which holds the possible combination of words. For better performance, a binary search will be performed against the Array. .NET Framework has an inbuilt method called BinarySearch. The only pre-condition to use this method is that the Array should be sorted. Again, we can use the inbuilt Sort method before invoking the BinarySearch method. The web service method will return the closest match for the passed in parameter.

The JavaScript "OnComplete" function will receive the text returned by the web service method. Once we have the text, all we have to do is to assign the text to the Textbox. To simplify, the above discussion can be summarized as follows:

1.    User types in text to the textbox.

2.    The "onkeyup" event for the textbox will fire a client side JavaScript function.

3.    The JavaScript function will invoke the web service method. The typed in text will be passed as a parameter to the web service method.

4.    The web service method will return the closest match for the passed in text.

5.    The JavaScript "OnComplete" function will receive the value returned by the web service method and assign it back to the Textbox.

Selecting the text inside the AutoComplete Textbox

One of the cosmetic features of an AutoComplete Textbox is to select the text in the Textbox. For example, if the value returned by the web service method is "hello," then we have to select the text "hello" inside the Textbox. This can be performed by the following code.

Listing 6

function SelectText(intStart, intLength)
{
  var myElement = document.getElementById('txtSearch');
  // get reference to the Textbox
  if (myElement.createTextRange)
  // If IE
  {
    var myRange = myElement.createTextRange();
    myRange.moveStart("character", intStart);
    myRange.moveEnd("character", intLength - myElement.value.length);
    myRange.select();
  }
  else if (myElement.setSelectionRange)
  // if FireFox
  {
    myElement.setSelectionRange(intStart, intLength);
  }
 
  myElement.focus();
}

Invoking the Web Service method only when specific keys are pressed

In order to make the AutoComplete Textbox more user friendly, we should not invoke the web service method for any keys pressed. For example, if the user presses the Backspace, we should invoke the web service method. If we allow, then the user will never be able to delete any text that he/she types in to the Textbox. Key trapping is a very simple process in JavaScript. Using the following line we can capture the ASCII value of the key pressed.

Listing 7

event.keyCode;

Once we have the ASCII value, we can control which keys should be allowed. Here is a code snippet which performs what we discussed in this section.

Listing 8

intKeyCode = event.keyCode;
// See if a valid key key is pressed such as 0-9, A-Z, a-z, Hyphen, Underscore
if (((intKeyCode >= 48) && (intKeyCode <= 57)) ||  // Numbers 0-9
((intKeyCode >= 65) && (intKeyCode <= 90)) ||  // Upper case A-Z
((intKeyCode >= 97) && (intKeyCode <= 122)) ||  // Lower case a-z
(intKeyCode == 189))
// Hyphen
{
  txtSearch = document.getElementById('txtSearch').value;
  strOldText = txtSearch;
  ret = myServices.WhatIsNext(txtSearch, OnComplete, OnError, OnTimeOut);
  return (true);
}
else
// return false.
return (false);

Web Service method which finds the closest match

Here is the code snippet for the web service method which searches for the closest match for the typed in text.

Listing 9

[WebMethod]public string WhatIsNext(string strText)
{
  int intIndex;
  string strWord;
 
  strWord = strText;
  intIndex = Array.BinarySearch(arrItems, strText);
  // if an exact match is found
  if (intIndex >= 0)
  {
    // if an Exact match is found, check the next item in the 
    // dictionary to see if it matches
    if (arrItems[intIndex + 1].Length >= strText.Length)
    {
      if (arrItems[intIndex + 1].Substring(0, strText.Length).ToLower() ==
        strText.ToLower())
      {
        strWord = arrItems[intIndex + 1];
      }
      else
      {
        strWord = arrItems[intIndex];
      }
    }
    else
    {}
  }
  else
  {
    if ((~intIndex) < (arrItems.Length))
    {
      // when we return the next word, make sure that it is really a closest match
      if (arrItems[~intIndex].Length >= strText.Length)
      {
        if (arrItems[~intIndex].Substring(0, strText.Length).ToLower() ==
          strText.ToLower())
        {
          strWord = arrItems[~intIndex];
        }
        else
        {}
      }
      else
      {}
    }
  }
    return strWord;
}
Live Demo

Downloads

Summary

The ASP.NET AJAX Control Toolkit already provides us with an AutoComplete Textbox control. You may ask why we are re-inventing the wheel. Well, this is a learning exercise to understand what is happening behind the scenes. I am not saying that this is how the control Toolkit AutoComplete Textbox is performed. This is one of the ways to build an AutoComplete Textbox. The essence of this article is to show how we can invoke a web service method from a client side JavaScript code. I hope this article comes in handy to you!



User Comments

Title: sdas   
Name: asd
Date: 2012-10-23 4:50:14 AM
Comment:
asd
Title: addasd   
Name: adasdadasd
Date: 2012-10-17 1:13:11 AM
Comment:
hasfhkagfaukgfya
Title: 1t   
Name: mmm
Date: 2012-09-13 11:47:03 AM
Comment:
test
Title: ijjkhjk   
Name: ansdfdf
Date: 2012-06-13 2:07:05 AM
Comment:
dfdsfdsfsdfdsf
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-05-20 11:29:49 PM
Comment:
[/pre]Cheap NFL,NBA,MLB,NHL
[url=http://www.jersey2shop.com/]Jerseys From China[/url]
[url=http://www.jersey2shop.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jersey2shop.com/]cheap China Jerseys[/url]
[url=http://www.jersey2shop.com/]Sports Jerseys China[/url]
[url=http://www.jersey2shop.com/NFL-Jerseys-c68/]NFL Jerseys China[/url]
[url=http://www.jersey2shop.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
NHL Jerseys China
[url=http://www.jersey2shop.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]We Are Professional China jerseys Wholesaler
[url=http://www.cheapjersey2store.com/]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url= http://www.cheapjersey2store.com/]2012 mlb all atar jerseys[/url]
[url= http://www.cheapjersey2store.com/ [/url]Cheap China Wholesael[/url]
[url= http://www.cheapjersey2store.com/]Wholesale jerseys From China[/url]
[url=http://www.cheapjersey2store.com/]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.cheapjersey2store.com/]Jerseys From China[/url]
[url=http://www.cheapjersey2store.com/NFL-Jerseys-c68]NFL jerseys China[/url]
[url=http://www.cheapjersey2store.com/NHL-Jerseys-c96/]NHL Jerseys China[/url]
[url=http://www.cheapjersey2store.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
[url=http://www.cheapjersey2store.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]
[url= http://www.cheapjersey2store.com/]China Jerseys[/url],Free Shipping
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.jerseycaptain.com/]cheap jerseys sale online [/url]
[url= http://www.jerseycaptain.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jerseycaptain.com/NFL-Jerseys-c68]cheap NFL jerseys China[/url]
[url=http://www.jerseycaptain.com/NHL-Jerseys-c96/]NHL Jerseys C
Title: HD   
Name: sam
Date: 2011-01-26 1:20:07 PM
Comment:
nice
Title: ram   
Name: ramin
Date: 2010-05-29 1:37:37 AM
Comment:
good
Title: flaw in code   
Name: arnab
Date: 2010-01-21 5:57:33 PM
Comment:
this is good but not the best, your autocomplete has the basic flaw that when the user presses enter, it submits the page or if he presses tab the word remains incomplete. Somehoe or other u shud allow the user to type 2 letters of a 10 letter word and so that user dont need to type the rest to keep the text in the textbox. good luck !!!
Title: facebook like autocomplete for asp.net   
Name: autosuggestor
Date: 2009-12-10 11:58:44 AM
Comment:
here is a fully customizable auto complete control (facebook like) for asp.net.

http://simp.lified.com
Title: Tyres Dealer   
Name: Tyres Dealer
Date: 2009-11-16 3:55:53 AM
Comment:
Wow, I never knew that Developing AutoComplete Textbox. That's pretty interesting…
Title: RE: multiple string return   
Name: martien
Date: 2009-07-09 9:38:00 AM
Comment:
http://pravinmagdum.wordpress.com/2009/06/15/auto-complete-textbox-control/ chk dis for multiple string returns in suto complete ..very naice article it solves my problem :)
Title: excellent mama   
Name: kanchan
Date: 2009-01-10 6:57:41 AM
Comment:
keka,nice, thank for giving and explaining the concept
Title: Mr.   
Name: Farrukh Malik
Date: 2008-11-06 8:43:29 AM
Comment:
good
Title: Mr.   
Name: Syed Mobarak
Date: 2008-11-05 3:20:17 PM
Comment:
Nice article. :)
Title: Exemple AutoComplete   
Name: Jafrany
Date: 2008-06-27 3:42:54 AM
Comment:
Video : http://www.asp.net/learn/ajax-videos/video-122.aspx
CodeScript: http://blogs.developpeur.org/cyril/archive/2007/10/16/autocomplete-keyvaluepair-identifiant-id-key-toolkit-autocompleteextender.aspx

;)
Title: autocomplete   
Name: arun
Date: 2008-04-10 8:19:57 AM
Comment:
It is realy nice concept for Autocomplete
Title: Developing AutoComplete Textbox using ASP.NET AJAX...   
Name: Balakrishnan
Date: 2008-03-26 3:18:24 AM
Comment:
Its good and light weight application to use in portal side...
Title: Firefox Issue   
Name: vct
Date: 2008-02-11 5:56:56 PM
Comment:
a great article, its working fine in IE, but it's not working in Firefox. Is there anything else that I need to do to get it to work in Firefox?
Title: mre description   
Name: eric
Date: 2008-01-02 2:18:48 PM
Comment:
PLease provide an example by merging everything together
Title: Extended AjaxToolkit Control Autocomplete looks like facebook   
Name: Ray
Date: 2007-12-19 5:03:38 PM
Comment:
Browsing the asp.net website I found this autocomplete control which is exactly like facebook. Someone extended the ajaxtoolkit control to make it function exactly like facebook.

This is the persons blog.
http://blogs.neudesic.com/blogs/pete_orologas/archive/2007/12/18/23739.aspx

This is where I found it.
http://forums.asp.net/t/1195936.aspx
Title: Its doesnt working properly   
Name: Thanigaimani
Date: 2007-12-07 5:35:47 AM
Comment:
Hi
Your article is ver nice .thanx but i have one doubt.
I get error in script manager tag,it display error for element script managar is not a known element,this is can occur in compilation time..
tel me how to use script manager tag..

Thanx

Reply me
Title: Auto Complet WebService Through AJAX   
Name: Nitin Sharma Software Engineer
Date: 2007-12-03 11:21:58 PM
Comment:
Gud One ..!! :-) :-)
Title: My variation of your code   
Name: Dan
Date: 2007-12-03 1:37:44 PM
Comment:
okay.. so I took what you made.. and I took code from a pure javascript textbox.. and I created my own based on the style of facebook's.

http://www.setlist.ca/fb/typeahead/

let me know what you think..

Also, just so you know, OnTimeOut is not used anymore. The timeout is combined in the OnError. Check out this page for more details:

http://dotnetslackers.com/columns/ajax/ASPNETAjaxWebService.aspx
Title: It does not work in ASP Page   
Name: Neerman
Date: 2007-11-29 5:07:16 PM
Comment:
Hi , I have a textbox in ASP.NET and when I use the code for the textbox, it shows null values
Title: AJAX Technology   
Name: Shailendra
Date: 2007-11-29 2:05:42 AM
Comment:
Gr8
Title: helloe   
Name: Devin Yang
Date: 2007-11-27 3:09:59 AM
Comment:
hello sir i want to get this feature
Title: Re: okay.. I was mistaken.. sort of..   
Name: Das
Date: 2007-11-26 7:05:02 PM
Comment:
Dan,

I followed your steps and the autocomplete textbox is working correctly.

The dictionary that I have given in the example is not sorted. In my example, I am sorting the array before finding the next word. Hope this helps.

:-)
Das
Title: okay.. I was mistaken.. sort of..   
Name: Dan
Date: 2007-11-26 4:18:25 PM
Comment:
typing in Apple the first time works..

BUT

if you type in Apple, then backspace 5 times, and type in apple again, and repeat this process, you get some strange results.

I've been trying to find a perfect autocomplete solution. I found one, (which ISN'T AJAX) which is close to facebook's but it uses a static list. I'm going to try to combine that solution, with your AJAX one, and hopefully it is the best of both worlds.
Title: It works !   
Name: Das
Date: 2007-11-26 3:36:31 PM
Comment:
Well, I was able to type in Apple. I will take a look at the Facebook's autocomplete feature ...
Title: doesn't work propery..   
Name: Dan
Date: 2007-11-26 3:09:09 PM
Comment:
I checked out your demo.. try typing apple.. the second the 1 appears, it changes what I typed to a10.. also it took me 3 times to be able to type beer..

Facebook's autocomplete textbox is one of the best I've ever seen.. perhaps you should model your after that one..






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 12:26:45 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search