weixin_33747129 2017-03-26 18:25 采纳率: 0%
浏览 26

在ASP MVC和Ajax中自动完成

i have a textbox and i want to make an autocomplete feature

i have this view i add the libraries but it does not respond at all

<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" />

the javascript code is this

$(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);
                }
            });
        },
    });

and here's the controller

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条回答 默认 最新

  • weixin_33736832 2017-03-26 19:04
    关注

    you have to make few changes to the code

    1) add jquery ui library by adding this into header

    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    

    2) change data: "{ 'prefix': '" + request.term + "'}" to data: { Prefix: request.term } remove "" from start and end

    so your code will be like this

     <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>
    
    评论

报告相同问题?