Thursday 4 June 2015

Jquery AutoComplete in asp.net using Webmethod

Here is the Script Code
function UserNameAutoComplete() { 
    $("#UserName").autocomplete
        ({
            source: function (request, response) {
                $.ajax
                    ({
                        url: "GSIRRegionConfigFSSCUserLsPg.aspx/GetADUsers",
                        data: "{ 'strADUser' : '" + $("#UserName").val() + "'}",
                        dataType: "json",
                        type: "POST",
                        async: true,
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            if (data.d.length == 0) {
                                $("#UserName").val('');
                            }
                            else {
                                $("#UserName").val();
                            }
                            response($.map(data.d, function (item) {
                                return {
                                    value: item
                                }
                            }));
                        },
                        failure: function (response) {
                            alert(response.d);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
            },
            select: function (event, ui) {
                varusrsplit = ui.item.value.split(",");
                document.getElementById('UserName').value = '';
                document.getElementById('UserName').value = varusrsplit[0];
                document.getElementById('UserID').value = varusrsplit[1];
                ui.item.value = ui.item.value.split(",")[0];
            },
            minLength: 3
        });

}
Here is the WebMethod
[WebMethod]
    public static List<string> GetADUsers(string strADUser)
    {
        string AutoCmpltVal = string.Empty;
        List<string> objList = new List<string>();
        string query = string.Format("Select distinct EmployeeName,UserAccount from AdmADUserMasterDetails where EmployeeName LIKE '%{0}%'", strADUser);

        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["SQLConnectionString"]))
        {
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr;
            con.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                AutoCmpltVal = (string)dr["EmployeeName"] + "," + (string)dr["UserAccount"];
                objList.Add(AutoCmpltVal);
            }
            return objList;
        }
    }