The ASP.NET Ajax Control Toolkit includes an “Autocomplete Extender“.

In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery.

jQuery UI makes “AutoComplete” very straight forward (Read the plugin spec here.)

Here is the behavior.

After the user enters 2 or more characters, then the UI starts to suggest values for the textbox.

In the case fo the jQuery UI Autocomplete plugin, the data can come from inside the page’s Document Object Model (DOM) or from a JavaScript callable web service.

For small data sets you may want to just send all the possible values to the browser with the rest of the page but AutoSuggest fields are most helpful when the number of possible value choices are too numerous to fit in a page’s dropdown control.

In this case, supplying the values via a service method is your choice and that’s what we’ll do in our example.

After creating a new website using the default ASP.NET Web Site Template, I’ll include a jQuery UI template CSS file and 3 JavaScript files.

  • jQuery
  • jQuery UI
  • a custom JavaScript file that contains my page specific code.

Then I’ll add an ASP.NET TextBox filed and associated label for the user to enter an email address in.

The markup for my default.aspx page is as follows:


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		                        Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='http://ajax.aspnetcdn.com/ajax/jquery.ui/
                   1.8.10/themes/redmond/jquery-ui.css'
      rel='stylesheet' type='text/css'/>

</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <hr /><br />

    <div>
            <label for='tbAuto'>Enter Email: </label>
             <asp:TextBox ID='tbAuto' class='autosuggest' runat='server'>
             </asp:TextBox>
    </div>
    <script type='text/javascript'
            src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'>
    </script>
    <script type='text/javascript'
     src='http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js'>
    </script>
    <script src='Scripts/PageScript.js' type='text/javascript'></script>
</asp:Content>

Next we need a service that will take a few characters of string as in input argument and return a collection of emaill addresses that match the beginning characters that the user entered.

SO, I’ll add an .ASMX service called EmployeeList.asmx

The service codebehind looks like this:



using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = &quot;http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EmployeeList : System.Web.Services.WebService
{
  [WebMethod]
    public List GetEmailSuggestions(string mail)
    {
    var emp = new Employee();
    var suggestionList = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
        return suggestionList.ToList();
    }
}

If you are new to service programming in ASP.NET you will note the [WebMethod] attribute on the GetMailSuggestions method will cause the method to be exposed via HTTP and the class itself is decorated with the [ScriptService] attribute which will make the class callable my JavaScript and provide facilities like JavaScript proxy generation.

Client side JavaScript cares little about how the results are generated and there are many ways to accomplish this sort of thing on the ASP.NET Server Side. ASMX is just one option, but it is often desirable because it is so richly tooled.

You will note that the code above makes use of a class named “Employee” which will contain our employee email address dataset.



using System.Collections.Generic;

///
/// Summary description for Employee
///
public class Employee
{
    public int ID { get; set; }
    public string Email { get; set; }

    public Employee()
    {
        //
  // TODO: Add constructor logic here
        //
    }

    public List GetEmployeeList()
    {
	List empList = new List();
	empList.Add(new Employee() { ID = 1, Email = 'Mary@fakemail.com' });
	empList.Add(new Employee() { ID = 2, Email = 'John@fakemail.com' });
	empList.Add(new Employee() { ID = 3, Email = 'Amy@fakemail.com' });
	empList.Add(new Employee() { ID = 4, Email = 'Kathy@fakemail.com' });
	empList.Add(new Employee() { ID = 5, Email = 'Larry@fakemail.com' });
	empList.Add(new Employee() { ID = 6, Email = 'Susanne@fakemail.com' });
	empList.Add(new Employee() { ID = 7, Email = 'John@fakemail.com' });
	empList.Add(new Employee() { ID = 8, Email = 'Josepf@fakemail.com' });
	empList.Add(new Employee() { ID = 9, Email = 'Robert@fakemail.com' });
	empList.Add(new Employee() { ID = 10, Email = 'Katherin@fakemail.com' });

    return empList;
    }

}

Now, refer back to the service code behind and take special note of line number 16 the “where” statement that will filter the list of email address to only include the ones that begin with the characters provided by the input field.

So, we have a page, a web service, and a class that contains the employee email address data.
Now we need to wire up the jQuery UI plugin to enable autocorrect.

Note the referenced PageScript.js file.


  $('.autosuggest').autocomplete({
        source: function (request, response) {
            $.ajax({
            url: 'EmployeeList.asmx/GetEmailSuggestions',
            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, callStatus, errorThrown) {
                alert(callStatus);
                }
            });
        },
        minLength: 2
    });
});

I think the script is pretty self explanatory but lets enumerate the high points.

Line #1 binds fields whose CSS class is set to “autosuggest” to the jQueryUI autocomplete plugin’s functionality.

Line #4 specifies the service URL and method name.

Line #10 specifies how to handle successfully returned data. (Note the types “Email” Item)

You can download the source code [ HERE ].