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

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

, 3 May 2010
Rate this:
Please Sign up or sign in to vote.
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:

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

<input id="autocomplete" />  

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

$(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:

<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:TextBox ID="txtautofromDB" runat="server"></asp:TextBox>

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

$(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 (Smile | :) separated string format.
Once the complete data is returned, it is split into an array of strings using the JavaScript's "split()" method.

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

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

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

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

$(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.

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.

[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:

{"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)

Share

About the Author

Devakumar Sai Chinthala
Founder Articledean.com & conveygreetings.com
United States United States
No Biography provided

Comments and Discussions

 
Questionhi PinmemberMember 108386412-Jul-14 0:06 
GeneralMy vote of 2 PinmemberEhsan yazdani rad20-Mar-13 12:48 
GeneralMy vote of 5 PinmemberMihai MOGA14-Dec-12 5:44 
GeneralMy vote of 4 PinmemberAbinash Bishoyi1-Jun-12 6:59 
QuestionCode for first solution fixed Pinmemberrama charan15-May-12 0:02 
GeneralMy vote of 2 Pinmembernmg1961-Dec-11 0:33 
AnswerExcellent Tutorial. Thank You! PinmemberJules Bartow10-Oct-11 5:46 
GeneralMy vote of 5 Pinmemberchetan thummar23-Apr-11 22:17 
GeneralMy vote of 3 PinmemberLukeWells5-Dec-10 22:36 
GeneralMy vote of 5 Pinmemberzhangtai16-Nov-10 17:56 
GeneralSubmit after selection Pinmembermaorray13-Aug-10 5:40 
GeneralIntergration Problem PinmemberMember 21849086-Aug-10 3:37 
Generalgetting error when record size greater than 1000 PinmemberEbbyStephen26-Jul-10 21:30 
General[My vote of 1] Yet another useless tutorial. PinmemberMackey1814-Jun-10 5:39 
GeneralRe: [My vote of 1] Yet another useless tutorial. PinmemberDevakumar Sai Chinthala14-Jun-10 6:02 
GeneralRequires complete data to come to the UI before u use the autocomplete feature. PinmemberThe Saint15-May-10 18:29 
GeneralRe: Requires complete data to come to the UI before u use the autocomplete feature. PinmemberDevakumar Sai Chinthala14-Jun-10 6:01 
GeneralGood Article PinmemberJitendra Zaa4-May-10 19:42 
GeneralCool Pinmemberjmunene3-May-10 9:19 

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
Web01 | 2.8.140827.1 | Last Updated 3 May 2010
Article Copyright 2010 by Devakumar Sai Chinthala
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid