【发布时间】:2020-05-29 23:44:33
【问题描述】:
我想在下拉列表中显示自动完成建议。但是建议没有显示。我已经尝试使用数据库和通过列表,但结果保持不变。
这是代码
模型包含 ID 和名称
HomeController.cs
public class HomeController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string Prefix)
{
//Note : you can bind same list from database
List<City> ObjList = new List<City>()
{
new City {Id=1,Name="abc" },
new City {Id=2,Name="def" },
new City {Id=3,Name="ghi" },
new City {Id=4,Name="jkl" },
};
//Searching records from list using LINQ query
var CityName = (from N in ObjList
where N.Name.StartsWith(Prefix)
select new { N.Name });
return Json(CityName, JsonRequestBehavior.AllowGet);
}
Index.cs
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<div class="col-md-12">
@Html.EditorFor(model => model.CityName, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</div>
}
如果有人可以指导我,我缺少什么? 提前致谢。
【问题讨论】:
-
你调试了吗? ajax 请求是否触发?
-
你调试了它,ajax 没有触发
-
你的领域的 id 是什么?尝试将其显式设置为 CityName:
new { htmlAttributes = new { @class = "form-control", @id = "CityName" } })
标签: jquery asp.net asp.net-mvc asp.net-core jquery-ui