从MVC 5中的数据库自动完成? [英] Autocomplete from database in MVC 5?

查看:90
本文介绍了从MVC 5中的数据库自动完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Service的模型,其中包括一些字段,但对我来说最重要的是ServiceName字段.我有下面显示的视图:

I have a model called Service, which includes a few fields, but the most important one for me is the ServiceName field. I have the view shown below:

@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数组手动提供自动完成源的话,它也可以正常工作.但是,我希望从数据库中读取源.因此,我创建了以下函数:

So, the point is that, when the user starts typing the service name, after 2 letters, I want to show the user suggestions, and use the autocomplete. I have already included the jQuery UI, and it works all fine, if I provide the autocomplete source manually as a JS array. But, I want the source to be read from the database. For this reason, I created the function below:

        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部分中,我有以下代码:

Then in my JS part, I have the following code:

$("#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()函数中收到一条错误消息时,我什至无法测试此代码段.我在return语句中收到一条消息:Cannot explicitly convert type List<AnonymousType> to JsonResult

I cannot even test this code segments, while I have an error message at my GetServiceNames() function. I get a message at the return statement saying: Cannot explicitly convert type List<AnonymousType> to JsonResult

如果有人可以帮助我解决此问题,并且告诉我我从数据库自动完成的逻辑是否正确(如果不正确,请提供更正),那么我会很高兴.

If someone can help me solve this problem, and also tell me whether my logic for autocomplete from database is correct (if not, please provide corrections), then I would be glad.

推荐答案

这里有些错误.要修复错误消息,您需要像这样将结果转换为Json:

There's a few things wrong here. To fix the error message, you need to convert your result to Json like this:

return Json(results);

此外,您没有将任何内容传递给操作.将操作更改为此:

Additionally you are not passing anything into the action. Change the action to this:

public JsonResult GetServiceNames(string term)
{
    var results = db.Services.Where(s => term == null || s.ServiceName.ToLower().Contains(term.ToLower())).Select(x => new { id = x.ServiceID, value = x.ServiceName }).Take(5).ToList();

    return Json(results, JsonRequestBehavior.AllowGet);
}

最后,您的jQuery不需要POST此请求,因此我将其更改为GET.总的来说,我建议将您的jQuery更改为类似的内容进行测试:

Finally, your jQuery doesn't need to POST this request so I would change it to a GET. Overall, I would suggest changing your jQuery to something like this to test:

$("#keywords-manual").autocomplete({
  source: "/Home/GetServiceNames",
  minLength: 2
})

这篇关于从MVC 5中的数据库自动完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆