Create new account I forgot my password    

TextBox AutoComplete with ASP.NET and jQuery UI
Rating: 8 user(s) have rated this article Average rating: 4.5
Posted by: Suprotim Agarwal, on 5/27/2010, in category "jQuery and ASP.NET"
Views: this article has been read 32392 times
Abstract: This article demonstrates how to use the jQuery UI AutoComplete widget to consume an ASP.NET Web Service that is JSON Serialized.

TextBox AutoComplete with ASP.NET and jQuery UI
 
This article demonstrates how to use the jQuery UI AutoComplete widget to consume an ASP.NET Web Service (EmployeeList.asmx) that is JSON Serialized. The data source for this web service is List<Employee> in the Employee.cs class. You can download this class from the source code attached with this article.
The Autocomplete widget is one of the widgets provided in jQuery UI and provides suggestions while you type into the field. jQuery UI is a free widget and interaction library built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.
[Note: If you are using jQuery with ASP.NET Controls, you may find my EBook 51 Recipes with jQuery and ASP.NET Controls helpful]
Let us first glance through the entire code with the jQuery UI AutoComplete widget added to the TextBox (tb)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(function() {
    $(".tb").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "EmployeeList.asmx/FetchEmailList",
                data: "{ 'mail': '" + request.term + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function(data) { return data; },
                success: function(data) {
                    response($.map(data.d, function(item) {
                        return {
                            value: item.Email
                        }
                    }))
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        },
        minLength: 2
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
    <label for="tbAuto">Enter Email: </label>
     <asp:TextBox ID="tbAuto" class="tb" runat="server">
     </asp:TextBox>
</div>
</div>
</form>
</body>
</html>
Now before explaining to you how this code functions, let us go through the WebService first. Assuming you have downloaded the source code and are looking at the EmployeeList.cs/vb file, you will observe that the method has been decorated with the [WebMethod] attribute to allow calls from client script
C#
[WebMethod]
public List<Employee> FetchEmailList(string mail)
{
    var emp = new Employee();
    var fetchEmail = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
    return fetchEmail.ToList();
}
VB.NET
<WebMethod>
Public Function FetchEmailList(ByVal mail As String) As List(Of Employee)
      Dim emp = New Employee()
      Dim fetchEmail = emp.GetEmployeeList().Where(Function(m) m.Email.ToLower().StartsWith(mail.ToLower()))
      Return fetchEmail.ToList()
End Function
Here the FetchEmailList(string mail) method calls the GetEmployeeList() method on the Employee class which returns a List<Employee>. We then filter the list using the filter string (mail) passed from the UI and then return the list of emails that match the filter string.
Note: If a method is not marked with [ScriptMethod] attribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON.
Going back to code we saw above, observe how the TextBox is wired to the AutoComplete widget.
 
$(function() {
    $(".tb").autocomplete({
        source: function(request, response) {
            $.ajax({
                // consume the webservice
        },
        minLength: 2
    });
});
To consume this web service using jQuery $.ajax(), two important points to note is that the request should be a POST request and the request’s content-type must be ‘application/json; charset=utf-8’. The code structure of the $.ajax() call looks similar to the following:
$.ajax({
    url: "EmployeeList.asmx/FetchEmailList",
    data: "{ 'mail': '" + request.term + "' }",
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function(data) {
 
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
});
 
Observe how the parameter (that the user types in the textbox) is passed to the webservice using data: "{ 'mail': '" + request.term + "' }" .You may need to add additional checks to format the data or validate it. Once the Ajax method is completed, the success function will be executed and the matching results (Email) will be returned using the following code.
dataFilter: function(data) { return data; },
success: function(data) {
    response($.map(data.d, function(item) {
        return {
            value: item.Email
        }
    }))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus);
}
Now when you browse the page and type the first 2 characters in the textbox, the jQuery UI AutoComplete widget added to the TextBox, provides suggestion that it pulls from the JSON enabled WebService as shown below
WebService
WebService_1
The entire source code of this article can be downloaded over here . I hope you liked the article and I thank you for viewing it.
 If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by web hosting on Tuesday, June 01, 2010 8:46 AM
i really need it,,,thanx alot...
Comment posted by jquerymaster on Sunday, July 11, 2010 10:33 AM
your example shows all data and matcing performed in autocomplete dropdown.can u plz solve this question

http://stackoverflow.com/questions/3222754/jquery-autocomplete-json-return-result-from-webservice-but-it-is-not-showing-in/3222800#3222800
Comment posted by Jimmy Tong on Thursday, August 19, 2010 9:48 PM

Thanks!
Nice article

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER