【发布时间】:2014-08-14 15:06:43
【问题描述】:
我有一个名为 Service 的模型,其中包含几个字段,但对我来说最重要的是 ServiceName 字段。我的视图如下所示:
@using (Html.BeginForm("Test", "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.ServiceName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ServiceName, 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>
}
所以,关键是,当用户开始输入服务名称时,在 2 个字母之后,我想向用户显示建议,并使用自动完成功能。我已经包含了 jQuery UI,如果我手动提供自动完成源作为 JS 数组,它就可以正常工作。但是,我希望从数据库中读取源。为此,我创建了以下函数:
public JsonResult GetServiceNames()
{
string keywords;
var results = db.Services.Where(s => keywords == null || s.ServiceName.ToLower().Contains(keywords.ToLower())).Select(x => new { id = x.ServiceID, value = x.ServiceName }).Take(5).ToList();
return results;
}
然后在我的 JS 部分,我有以下代码:
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax({
url: "Home/GetServiceNames",
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
});
我什至无法测试此代码段,而我的 GetServiceNames() 函数出现错误消息。我在退货声明中收到一条消息:Cannot explicitly convert type List<AnonymousType> to JsonResult
如果有人能帮我解决这个问题,并告诉我我从数据库自动完成的逻辑是否正确(如果不正确,请提供更正),我会很高兴。
【问题讨论】:
标签: javascript jquery ajax asp.net-mvc autocomplete