我在项目中遇到了自动完成的问题。我使用的是MVC4,已经按照Json部分的要求进行了正确的设置。但我不确定问题是出在jQuery上还是我的控制器上。 以下是代码:
public ActionResult Index()
{
EmployeeContext db = new EmployeeContext();
return View(db.Employees);
}
[HttpPost]
public ActionResult Index(string Search_Data)
{
EmployeeContext db = new EmployeeContext();
List<Employee> employees;
if (string.IsNullOrEmpty(Search_Data))
{
employees = db.Employees.ToList();
}
else
{
employees = db.Employees
.Where(s => s.EmpName.StartsWith(Search_Data)).ToList();
}
return View(employees);
}
public JsonResult GetEmployees(string term)
{
EmployeeContext db = new EmployeeContext();
List<string> employees = db.Employees.Where(s => s.EmpName.StartsWith(term))
.Select(x => x.EmpName).ToList();
return Json(employees, JsonRequestBehavior.AllowGet);
}
以下脚本用于我的index.cshtml页面:
<link href="~/Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css"/>
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetEmployees","Employee")',
minLength: 1
});
});
</script>
问题出在GetEmployees方法没有被调用,我能够通过输入字符串来搜索数据,但自动完成无法正常工作。