自动完成Asp mvc&阿贾克斯

时间:2017-03-26 18:25:40

标签: javascript jquery json ajax asp.net-mvc

我有一个文本框,我想制作一个自动完成功能

我有这个观点 我添加了库,但它根本没有响应

<link href="~/Content/themes/base/autocomplete.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-3.1.1.js"></script>
<input type="text" id="q" name="q" placeholder="Enter the text please" />

javascript代码就是这个

$(document).ready(function () {
    $("#q").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/Book/AutoComplete/',
                data: "{ 'prefix': '" + request.term + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.Name, value: item.Name };
                    }))
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            });
        },
    });

这是控制器

public JsonResult AutoComplete(string prefix)
{
    var book = db.Book.Where(x => x.Name.Contains(prefix)).Select(x =>x.Name).ToList();
    return Json(book, JsonRequestBehavior.AllowGet);
}

1 个答案:

答案 0 :(得分:0)

您必须对代码进行一些更改

1)通过将此添加到标题

中来添加jquery ui库
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

2)data: "{ 'prefix': '" + request.term + "'}"更改为data: { Prefix: request.term }从开始和结束时删除""

所以你的代码就像这样

 <script type="text/javascript">

    $(document).ready(function () {
        $("#q").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Book/AutoComplete/",
                    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>