<script type="text/javascript">
$(function () {
$("[id$=txtAuto]").autocomplete({
source: function (request, response) {
$.ajax({
url: "NameList.asmx/GetNameList",
data: "{ 'Name': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var Details = [];
for (i = 0; i < data.d.length; i++) {
Details[i] = data.d[i].Name;
} response(Details);
},
error: function (result) {
}
});
}
});
});
</script>
public class NameList : System.Web.Services.WebService
{
[WebMethod]
public List<UserNameList> GetNameList(string Name)
{
var emp = new UserNameList();
var fetchName = emp.GetEmpList()
.Where(m => m.Name.ToLower().StartsWith(Name.ToLower()));
return fetchName.ToList();
}
}
public class UserNameList
{
public int ID { get; set; }
public string Name { get; set; }
public List<UserNameList> GetEmpList()
{
List<UserNameList> emp = new List<UserNameList>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT name as txt from lib_memtable where name like @SearchText +'%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("@SearchText", Name);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
emp.Add(obj_result["name"].ToString().TrimEnd());
}
}
}
return emp;
}
emp.Add(obj_result["name"].ToString().TrimEnd());
答案 0 :(得分:2)
在你的SQL中你有Select DISTINCT name as txt
。
当您向下阅读时,请将其称为name
,而不是txt
。
如果你将while内的行改为this,它应该可以工作
emp.Add(obj_result["txt"].ToString().TrimEnd());
答案 1 :(得分:0)
如果您只是返回字符串列表,则应将UserNameList.GetEmpList()
的返回类型更改为List<string>
并相应地修改代码,它应如下所示:
public class UserNameList
{
public int ID { get; set; }
public string Name { get; set; }
public List<string> GetEmpList()
{
List<string> emp = new List<string>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT name as txt from lib_memtable where name like @SearchText +'%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("@SearchText", Name);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
emp.Add(obj_result["name"].ToString().TrimEnd());
}
}
}
return emp;
}
}