narasiman rao

narasiman rao

  • NA
  • 519
  • 768.9k

Autocomplete extender using JQuery

Mar 6 2016 8:20 AM
 
  My source code as follows

<script type="text/javascript">
$(function () {
$("[id$=txtSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
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$=hfCustomerId]").val(i.item.val);
},
minLength: 1
});
});


html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body

<form id="form1" runat="server">
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />

</form>
</body>
</html>


Aspx code as follows

public static string[] GetCustomers(string prefix)

{
List customers = new List();
using (SqlConnection conn = new SqlConnection())
{


SqlConnection strconnection = new SqlConnection("Data Source=GOD-PC;Initial Catalog=Test;Trusted_Connection=true");

using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactName, CustomerId from customers where ContactName like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefix);
cmd.Connection = strconnection;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
}
}
conn.Close();
}
}
return customers.ToArray();
}


protected void Submit(object sender, EventArgs e)
{

string customerName = Request.Form[txtSearch.UniqueID];
string customerId = Request.Form[hfCustomerId.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName + "\\nID: " + customerId + "');", true);

}

In run mode as follows

Enter Search Name        textbox        (Submit button)

In textbox type the contacname and click the submit button. when i click the submit button the CustomerId will be displayed from the customers table

but when i click the submit button id is not displayed.

Please help me what is the problem in my above code.
 

Answers (1)