1,标签
<input type="text" data-autocomplete-source="@Url.Action("QuickSearch","Demo")" />
2,需要引用样式和脚本
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")"></script>
3,脚本代码
<script type="text/javascript">
$(function () {
$("input[data-autocomplete-source]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete-source") });
});
});
</script>
4,控制器代码
public JsonResult QuickSearch(string term)
{
var s = db.Demos.Where(r => r.Name.Contains(term)).ToList().Select(a => new { value = a.Name });
//必须允许来自客户端的GET请求。不过这样会出现安全隐患
return Json(s, JsonRequestBehavior.AllowGet);
}