Code in
Default.aspx
<body>
<form id="form1" runat="server">
<div>
Name:
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"
type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function
() {
$("#txtCity").autocomplete({
source: function (request, response) {
var
param = { cityName: $('#txtCity').val() };
$.ajax({
url: "Default.aspx/GetEmployeeName",
data:
JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return
data; },
success: function (data) {
console.log(data);
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2//minLength as 2, it means when ever user enter 2
character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
</body>
</body>
Code in
Default.aspx.cs
[WebMethod]
public static List<string> GetEmployeeName(string
cityName)
{
List<string> empResult = new
List<string>();
using
(SqlConnection con = new SqlConnection(@"Data Source=SHANKAR\SQL2008R2;Initial Catalog=SMPL;Persist Security Info=True;User ID=sa;Password=********"))
{
using
(SqlCommand cmd = new
SqlCommand())
{
cmd.CommandText = "select EmployeeName from Employee where
EmployeeName LIKE ''+@SearchEmpName+'%'";
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("@SearchEmpName",
cityName);
SqlDataReader
dr = cmd.ExecuteReader();
while
(dr.Read())
{
empResult.Add(dr["EmployeeName"].ToString());
}
con.Close();
return
empResult;
}
}
}