gpt4 book ai didi

javascript - 如何使用 MVC 5 中数据库中的值进行自动完成?

转载 作者:行者123 更新时间:2023-11-29 23:59:29 25 4
gpt4 key购买 nike

目前,我有以下代码:

ma​​in.js:

$(function () {
var keys = ["test1", "test2", "test3", "test4"];

$("#keywords-manual").autocomplete({
minLength: 2,
source: keys
});
});

测试.cshtml:

@model App.Models.Service
@{
ViewBag.Title = "Test";
}

<script src="~/Scripts/main.js"></script>

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

@using (Html.BeginForm("SaveAndShare", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<h4>Create a new request.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.ServiceType, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ServiceType, new { @class = "form-control", @id = "keywords-manual" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit!" />
</div>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

重点是,目前我刚刚为自动完成功能提供了 4 个常量值。但后来我创建了一个数据库和一个名为“services”的表,该表来 self 名为 Service 的模型。我已经向表中提供了几行值。我的表中有一个名为 ServiceType 的字段,我希望自动完成功能将该列的值作为源。请注意,我已将数据库托管在 Azure 中,并且它是 MySQL,不过,我认为这并不重要。您能告诉我如何将位于我的服务表内的 ServiceType 列的值作为源吗?

最佳答案

据我所知,你的问题应该是这样的:

$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetServiceTypes",
data: "{ 'keywords': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id
}
}))
}
});
},
minLength: 2
});

还有 Controller ,

YourContext db = new YourContext();
public JsonResult GetServiceTypes() {
db.ServiceType.Where(s => keywords == null || s.Name.ToLower()
.Contains(keywords.ToLower()))
.Select(x => new { id = x.ServiceTypeID, value = x.ServiceTypeName }).Take(5).ToList();
return result;
}

对任何拼写错误表示歉意,但这应该是它的要点。如果您需要搜索多个关键字,请在 Controller 方法中,将“keywords-manual”中的值拆分为字符串数组,然后使用 foreach 循环或类似方法来匹配每个值,将匹配项添加到总列表中每次。

** 我说的是字符串数组,这很老派,把它分成一个列表:)

关于javascript - 如何使用 MVC 5 中数据库中的值进行自动完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141470/

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