Monday, August 23, 2010

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:



See full details: http://www.c-sharpcorner.com/UploadFile/rkpal80/2806/