我正在使用jquery自动完成功能。以下代码用于从数据库中获取数据。
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString("q");
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings("conio").ConnectionString;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = ("select cityCode,city,metro,status from cities where (cityCode like @SearchText)");
cmd.Parameters.AddWithValue("@SearchText", "%" + prefixText + "%");
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
MySqlDataReader sdr = cmd.ExecuteReader;
while (sdr.Read) {
sb.Append(sdr("cityCode")).Append(Environment.NewLine);
}
conn.Close();
context.Response.Write(sb.ToString);
}
此代码正常运行,但我需要再添加一项功能。通过显示cityCode,我还想显示相应的城市名称以及f.g
PNQ(PUNE)
这里PNQ是代码& PUNE是城市的名字所以我想在建议结果这样显示。但是当用户选择任何值,然后在文本框中,它应该只获取代码而不是名称。任何人都可以指导我如何做到这一点?
答案 0 :(得分:0)
没有内置方法可以做到这一点。相反,您应该覆盖select事件,并自己更新输入值;
//You need to pass data like following from code behind:
[{
"label": "PNQ(PUNE)",
"value": "PNQ"
}, {
"label": "PNQ1(PUNE1)",
"value": "PNQ1"
}]
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactName, CustomerId from Customers where " +
"ContactName like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefix);
cmd.Connection = conn;
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();
}
}
$("#autocomplete").autocomplete({
select: function (event, ui) {
//Instead of ui.item.label need to use ui.item.value
$(this).val(ui.item.value);
},
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/page.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);
}
});
},
minLength: 1
});