【发布时间】:2016-03-10 12:57:31
【问题描述】:
我在 ASP.NET c# 和 MySQL 数据库中工作。
我需要使用 AJAX 从数据库中制作自动完成文本框,我已经在网上尝试过这个教程。
但是当名称由多个单词组成时,我会遇到问题,例如:
名称:飞机
进行搜索
姓名:规划师
不起作用,因为在 PostBack Page 之后,TextBox 中列表中的选定值只有 Planner 并且搜索返回为空。
如果删除TextBox txtCp上的属性
AutoPostBack="true"
然后按Enter搜索正在运行的脚本。
为什么?
我的代码:
<asp:TextBox ID="txtCp" runat="server" OnTextChanged="txtCp_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:HiddenField ID="hfCp" runat="server" />
[WebMethod]
public static string[] GetCustomers(string prefix)
{
List<string> customers = new List<string>();
using (OdbcConnection conn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd = new OdbcCommand())
{
cmd.CommandText = "SELECT Name FROM doName WHERE Name LIKE CONCAT('%',?,'%'); ";
cmd.Parameters.AddWithValue("param1", prefix);
cmd.Connection = conn;
conn.Open();
using (OdbcDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(string.Format("{0}", sdr["Name"].ToString().ToUpper()));
}
}
conn.Close();
}
}
return customers.ToArray();
}
protected void txtCp_TextChanged(object sender, EventArgs e)
{
BindData();
}
$(function () {
$("[id$=txtCp]").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$=hfCp]").val(i.item.val);
},
minLength: 1
});
});
你能帮我解决问题吗?
提前致谢。
编辑#1
第一段:
第二段:
测试代码:
protected void txtCp_TextChanged(object sender, EventArgs e)
{
CustomerId = hfCustomerId.Value;
Text = txtSearch.Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + CustomerId + "\\nID: " + Text + "');", true);
}
【问题讨论】:
标签: c# jquery mysql asp.net ajax