In your ASPX page:
<script type="text/javascript">
$(function () {
$("[id$=txtLastNameSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("Home.aspx/GetLastName") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function(item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}));
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=LastName]").val(i.item.val);
},
minLength: 3
});
});
</script>
Enter Last Name: <asp:TextBox ID="txtLastNameSearch" runat="server" />
<asp:HiddenField ID="LastName" runat="server" />
And in your code behind:
[WebMethod]
public static string[] GetLastName(string prefix)
{
var lastName = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT LastName FROM tbl_Profile WHERE LastName LIKE @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefix);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
lastName.Add(sdr["LastName"].ToString());
}
}
conn.Close();
}
}
return lastName.ToArray();
}
No comments:
Post a Comment