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:
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 (:) 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); }
catch (Exception ex)
{
string exp = ex.ToString(); }
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:
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:
event
: Contains the source element, which caused the event.
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(); }
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:
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:
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