gpt4 book ai didi

c# - 如何在 MVC 中实现自动完成文本框

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:59 24 4
gpt4 key购买 nike

我在使用硬编码数据自动完成文本框时遇到问题,我的 json“搜索”方法没有触发我不知道问题出在哪里。请提前帮助我谢谢

Model:

  public class Locations
{

public int Id { get; set; }
public string Name { get; set; }

}

Controller:

public JsonResult Search(string query)
{
List<Locations> locations = new List<Locations>()
{
new Locations() {Id = 1, Name = "London"},
new Locations() {Id = 2, Name = "Walles"},
new Locations() {Id = 3, Name = "Birmingham"},
new Locations() {Id = 4, Name = "Edinburgh"},
new Locations() {Id = 5, Name = "Glasgow"},
new Locations() {Id = 6, Name = "Liverpool"},
new Locations() {Id = 7, Name = "Bristol"},
new Locations() {Id = 8, Name = "Manchester"},
new Locations() {Id = 9, Name = "NewCastle"},
new Locations() {Id = 10, Name = "Leeds"},
new Locations() {Id = 11, Name = "Sheffield"},
new Locations() {Id = 12, Name = "Nottingham"},
new Locations() {Id = 13, Name = "Cardif"},
new Locations() {Id = 14, Name = "Cambridge"},
new Locations() {Id = 15, Name = "Bradford"},
new Locations() {Id = 16, Name = "Kingston Upon Hall"},
new Locations() {Id = 17, Name = "Norwich"},
new Locations() {Id = 18, Name = "Conventory"}

};
List<string> Loc;
Loc = locations.Where(x => x.Name.StartsWith(query.ToLower())).Select(x => x.Name).ToList();
return Json(Loc, JsonRequestBehavior.AllowGet);
}

View:

@model IEnumerable<SearchBox.Models.Locations>
@using SearchBox.Models
@{
ViewBag.Title = "Index";
}

<link href="~/Content/Autocomplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Autocomplete/jquery-ui.js"></script>
<link href="~/Content/Autocomplete/jquery-ui.theme.css" rel="stylesheet" />

<script type="text/javascript">
$("#tags").autocomplete({
source: '@Url.Action("Search")'
});
</script>

<input type="text" id="tags" />

最佳答案

您需要发出 ajax 请求,而不是只在数据源中传递 url。

<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/jquery-1.12.4.js"></script>
<script src="~/Content/jquery-ui.js"></script>

<input type="text" id="tags" />

<script type="text/javascript">
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("Search")',
dataType: "jsonp",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {

}
});
</script>

查看使用方法autocomplete with ajax request .

关于c# - 如何在 MVC 中实现自动完成文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43535347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com