Click here to Skip to main content
15,867,594 members
Articles / Web Development / ASP.NET

3 Different Approaches for Implementing the JQuery Autocomplete with ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.29/5 (38 votes)
3 May 2010CPOL4 min read 222.8K   8.9K   80   22
3 different approaches for implementing the Jquery autocomplete with ASP.NET
JQ-Autocomplete

Introduction

This article describes various approaches of using the autocomplete feature of JQuery with ASP.NET.

Background

Inspite of many autocomplete plug-ins available in the market, finally the JQuery team has came up with a good autocomplete functionality in the recent release of jquery 1.4.2.
With the new autocomplete, the implementation can be done in more than one way, which is good and easy for the developers.

Prerequisite

  • A web based browser to view the web page
  • Good knowledge of HTML and JQuery
  • ASP.NET
  • Knowledge of ASP.NET Webservice
  • Understanding of JSON data format

AutoComplete: Source Array

Out of various implementations of autocomplete, this approach is simple and straightforward.
Let's start with the implementation details:

First Step: Include the reference to the JQuery library in the head. In this case:

HTML
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css 
	rel="stylesheet" type="text/css"/>        

Second Step: Add a text box to the page.

HTML
<input id="autocomplete" />  

Third Step: Add the following code inside the document.ready:

JavaScript
$(document).ready(function() {
    $("input#autocomplete").autocomplete({
            source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
        });              
}

There you go, you are done with the implementation details of the autocomplete. Once the webpage is browsed, here is the preview of the output:

Image1.PNG

AutoComplete: Data from a Webservice

Alright, we are done with the first approach of implementation, let's look at the second approach.

In this approach we will extend the implementation by fetching the data from a webservice.
In order to fetch the data from a webservice, let's make use of JQuery's built in Ajax functionality.

First Step: Include the reference to the jquery library in the head. In this case:

HTML
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css 
	rel="stylesheet" type="text/css"/>

Second Step: Add a text box to the page:

ASP.NET
<asp:TextBox ID="txtautofromDB" runat="server"></asp:TextBox>

Third Step: Add the following code inside the document.ready:

JavaScript
$(document).ready(function() {
        
    $.ajax({
        type: "POST",
        url: "/Service/WSDataService.asmx/GetStates",
        dataType: "json",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            var datafromServer = data.d.split(":");
            $("[id$='txtautofromDB']").autocomplete({
                source: datafromServer
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
        }
    });
}

Fourth Step: In this step, let's go over the server side implementation details. I am going to outline the details.

For the purpose of invoking the webmethod from client-side framework, "GetStates()" web method has been added, which returns the data in a colon (:) separated string format.
Once the complete data is returned, it is split into an array of strings using the JavaScript's "split()" method.

C#
[WebMethod]
public string GetStates()
{
    StringBuilder sbStates = new StringBuilder();
             
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("~/Data/States.xml"));
    try
    {
        foreach (XmlElement xnl in doc.DocumentElement.ChildNodes)
        {
            sbStates.AppendFormat("{0}:",xnl.Attributes["name"].Value);
        }

        sbStates = sbStates.Remove(sbStates.Length - 1, 1); //Removes the extra ":"
    }
    catch (Exception ex)
    {
        string exp = ex.ToString(); 	//Setup a breakpoint here 
				//to verify any exceptions raised.
    }
    return sbStates.ToString();
}

A sample output of the webmethod, GetStates() is as given below:

ALABAMA:ALASKA:AMERICAN SAMOA:ARIZONA:ARKANSAS:CALIFORNIA:COLORADO:
CONNECTICUT:DELAWARE:DISTRICT OF COLUMBIA  

Once the webpage is browsed, here is the preview of the output:

Image2.PNG

AutoComplete: Source Custom Data Format

Alright, we are done with the second approach of implementation, let's look at the third approach.
In this approach, we will extend the implementation to a real world example by fetching the custom data from a webservice in a JSON format.

First Step: Include the reference to the JQuery library in the head.

HTML
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.custom.min.js" type="text/javascript"></script>
<link href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css 
	rel="stylesheet" type="text/css"/>

Second Step: Add a text box to the page, which serves as the autocomplete textbox.
Once the user selects an item (state) from the list, the state's code is displayed in the selected value.

HTML
<input id="project" />
<div id="selectedValue"></div>  

Third Step: Add the following code inside the document.ready:

JavaScript
$(document).ready(function() {   
    $.ajax({
        type: "POST",
        url: "/Service/WSDataService.asmx/GetStatesWithAbbr",
        dataType: "json",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            $('#project').autocomplete({
                minLength: 0,
                source: data.d,
                focus: function(event, ui) {
                    $('#project').val(ui.item.Name);
                    return false;
                },
                select: function(event, ui) {
                    $('#project').val(ui.item.Name);
                    $('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
                    return false;
                }
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

Autocomplete event, which is worth making a note of is "select". Once the user selects an item from the list, "select" event is fired.
"Select" event contains 2 parameters:

  1. event: Contains the source element, which caused the event.
  2. ui: Contains the UI elements as well as source of data attached with the selected item. In our case, it would be "Name" & "Abbreviation" elements.

Fourth Step: In this step, let's go over the server side implementation details. A custom class "State" has been created to store the values of the state.

C#
public class State
{
    string _name;
    string _value;

    public string value
    {
        get { return _value; }
        set { _value = value; }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    string _abbr;

    public string Abbreviation
    {
        get { return _abbr; }
        set { _abbr = value; }
    }
}

"GetStatesWithAbbr" returns the data in JSON format. This is done with the help of "ScriptMethod(ResponseFormat = ResponseFormat.Json)" attribute.

C#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<State> GetStatesWithAbbr()
{
    List<State> sbStates = new List<State>();

    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("~/Data/States.xml"));
    try
    {
        foreach (XmlElement xnl in doc.DocumentElement.ChildNodes)
        {
            State st = new State();
            st.Name = xnl.Attributes["name"].Value;
            st.Abbreviation = xnl.Attributes["abbreviation"].Value;
            st.value = xnl.Attributes["name"].Value;
            sbStates.Add(st);
        }
    }
    catch (Exception ex)
    {
        string exp = ex.ToString();	//Setup a breakpoint here 
				//to verify any exceptions raised.
    }
    return sbStates;
}

A sample JSON response returned from "GetStatesWithAbbr" will look as below:

JavaScript
{"d":[{"__type":"ArticleDean.web.Service.State",
	"value":"ALABAMA","Name":"ALABAMA","Abbreviation":"AL"},
{"__type":"ArticleDean.web.Service.State",
	"value":"ARIZONA","Name":"ARIZONA","Abbreviation":"AZ"},
{"__type":"ArticleDean.web.Service.State",
	"value":"ARKANSAS","Name":"ARKANSAS","Abbreviation":"AR"},
{"__type":"ArticleDean.web.Service.State",
	"value":"CALIFORNIA","Name":"CALIFORNIA","Abbreviation":"CA"},
{"__type":"ArticleDean.web.Service.State",
	"value":"COLORADO","Name":"COLORADO","Abbreviation":"CO"},
{"__type":"ArticleDean.web.Service.State",
	"value":"CONNECTICUT","Name":"CONNECTICUT","Abbreviation":"CT"},
{"__type":"ArticleDean.web.Service.State",
	"value":"WYOMING","Name":"WYOMING","Abbreviation":"WY"}]}

A sample output of the webmethod (in debug mode) is as below:

Image3.PNG

Note: While returning the custom data format (JSON), it is important to have a property by the name "value" in the results collection.

Once the webpage is browsed, here is the preview of the output:

Image2.PNG

Remarks

JQuery is one of the powerful clientside frameworks which is widely accepted. With the recent release of 1.4.2, a couple of new functionalities/features have been introduced, of which "Autocomplete" is one of them.
This article demonstrates 3 different approaches of the implementation. Apart from the above demonstrated methods, there are a couple more approaches available with "Autocomplete", which includes call back to a remote service.

References

History

  • 3rd May, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Articledean.com & conveygreetings.com
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIs it efficient? Pin
skand1-Mar-15 6:17
skand1-Mar-15 6:17 
GeneralAppreciation Pin
kalsa16-Jan-15 18:26
kalsa16-Jan-15 18:26 
SuggestionVery helpful. But needs detailed information for a newbie. Pin
Member 105909495-Dec-14 2:15
Member 105909495-Dec-14 2:15 
Questionhi Pin
Member 108386412-Jul-14 0:06
Member 108386412-Jul-14 0:06 
GeneralMy vote of 2 Pin
Ehsan yazdani rad20-Mar-13 12:48
Ehsan yazdani rad20-Mar-13 12:48 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA14-Dec-12 5:44
professionalȘtefan-Mihai MOGA14-Dec-12 5:44 
GeneralMy vote of 4 Pin
Abinash Bishoyi1-Jun-12 6:59
Abinash Bishoyi1-Jun-12 6:59 
QuestionCode for first solution fixed Pin
rama charan15-May-12 0:02
rama charan15-May-12 0:02 
GeneralMy vote of 2 Pin
nmg1961-Dec-11 0:33
nmg1961-Dec-11 0:33 
AnswerExcellent Tutorial. Thank You! Pin
Jules Bartow10-Oct-11 5:46
Jules Bartow10-Oct-11 5:46 
GeneralMy vote of 5 Pin
chetan thummar23-Apr-11 22:17
chetan thummar23-Apr-11 22:17 
GeneralMy vote of 3 Pin
LukeWells5-Dec-10 22:36
LukeWells5-Dec-10 22:36 
GeneralMy vote of 5 Pin
zhangtai16-Nov-10 17:56
zhangtai16-Nov-10 17:56 
GeneralSubmit after selection Pin
maorray13-Aug-10 5:40
maorray13-Aug-10 5:40 
GeneralIntergration Problem Pin
Member 21849086-Aug-10 3:37
Member 21849086-Aug-10 3:37 
Generalgetting error when record size greater than 1000 Pin
EbbyStephen26-Jul-10 21:30
EbbyStephen26-Jul-10 21:30 
General[My vote of 1] Yet another useless tutorial. Pin
Mackey1814-Jun-10 5:39
Mackey1814-Jun-10 5:39 
GeneralRe: [My vote of 1] Yet another useless tutorial. Pin
Devakumar Sai Chinthala14-Jun-10 6:02
Devakumar Sai Chinthala14-Jun-10 6:02 
GeneralRequires complete data to come to the UI before u use the autocomplete feature. Pin
The Saint15-May-10 18:29
The Saint15-May-10 18:29 
GeneralRe: Requires complete data to come to the UI before u use the autocomplete feature. Pin
Devakumar Sai Chinthala14-Jun-10 6:01
Devakumar Sai Chinthala14-Jun-10 6:01 
GeneralGood Article Pin
Jitendra Zaa4-May-10 19:42
Jitendra Zaa4-May-10 19:42 
Good Article
GeneralCool Pin
johnmunene3-May-10 9:19
johnmunene3-May-10 9:19 

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.