【发布时间】:2016-05-13 09:23:28
【问题描述】:
我是初学者,我正在尝试使用 ASP.Net MVC 5 开发一个自动完成搜索框。我使用 Northwind 数据库和实体框架 6。
这是我的 index.cshtml 代码
@model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetCustomers")'
});
});
</script>
@using (@Html.BeginForm())
{
<b>Name : </b>
@Html.TextBox("searchTerm", null, new { @id = "txtSearch" })
<input type="submit" value="Search" />
}
这是我的 CustomerController 类
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
当我通过输入关键字并单击提交按钮搜索记录时,此代码正在工作。但是 jquery 脚本不能调用 GetCustomer 方法。检查元素显示以下错误。
Uncaught TypeError: $(...).autocomplete is not a function
文本框应向文本框本身建议公司名称。如何纠正这个问题。
谢谢。
【问题讨论】:
-
您是否正确添加了 jQuery?在浏览器中查看渲染页面 ViewSource。
-
根据错误消息,您没有正确加载 jQuery 或其插件
-
我尝试通过关注this 视频来做到这一点。这就是我将 Jquery 添加到我的视图的方式 错了吗?
-
将你的脚本标签移动到页面底部
标签: c# jquery asp.net asp.net-mvc