Developing Autosuggest using JQuery and Webservices


Autocomplete is an input field that enable users to quickly finds and selecting some value.

By giving an autocompleted field on entering some value  into it.

The code starts searching for matching entry and displays a list of matching values.

By entering more characters, the user can filter down the list to better matches.

Namespace to be import

using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

autosuggest.asmx (a web service file)

[ScriptService]
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class AutoComplete : System.Web.Services.WebService
    {
        public class Employee
        {
            public int ID { get; set; }
            public string Email { get; set; }
            public Employee()
            {
                //
                // TODO: Add constructor logic here
                //
            }
            public List<Employee> GetEmployeeList(string prefixText)
            {
                List<Employee> empList = new List<Employee>();
                DataSet dtst = new DataSet();
                SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["EAEConnectionInstance"].ConnectionString);
                string strSql = "SELECT FirstName  FROM EAE_UserProfile_Tbl WHERE FirstName LIKE '%" + prefixText + "%' OR LastName LIKE '%" + prefixText + "%'";
                SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
                sqlCon.Open();
                SqlDataAdapter sqlAdpt = new SqlDataAdapter();
                sqlAdpt.SelectCommand = sqlComd;
                sqlAdpt.Fill(dtst);
                int i = 0;
                try
                {
                    foreach (DataRow rdr in dtst.Tables[0].Rows)
                    {
                        empList.Add(new Employee() { ID = i, Email = rdr["FirstName"].ToString() });
                        i++;
                    }
                }
                catch { }
                finally
                {
                    sqlCon.Close();
                }
                return empList;
            }
        }
        [WebMethod]
        public List<Employee> FetchEmailList(string mail)
        {
            var emp = new Employee();
            var fetchEmail = emp.GetEmployeeList(mail)
                //.Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
            .Where(m => m.Email.ToLower().Contains(mail.ToLower()));
            return fetchEmail.ToList();
        }
    }

aspx Page:

<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 () {
                  $(".searchText").autocomplete({
                      source: function (request, response) {
                          $.ajax({
                              url: "AutoComplete.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>