jquery autocomplete不过滤并显示所有结果

时间:2016-02-15 11:26:53

标签: jquery json autocomplete asp.net-mvc-5

我有这个简单的JsonResult动作,我需要根据名称进行过滤,如果它不存在,请将名称添加到Db中。然而,我的自动完成结果只是在键入2个字母而忽略了我的输入之后将我的所有列表都放到了我的表中 我的代码:

   public JsonResult GetSubjectsName(string term)
    {
        var results = db.Subject.Where(s => term == null ||
        s.SubjectName.ToLower().Contains(term.ToLower())).Select(x => new
        { id = x.SubjectId, value = x.SubjectName  }).Distinct().ToList();
        return Json(results, JsonRequestBehavior.AllowGet);
    }
<script type="text/javascript">
   $("#term").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "GetSubjectsName",
                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,
    });

1 个答案:

答案 0 :(得分:2)

上述代码的问题是您的操作GetSubjectsName采用名为term的参数,但在传入ajax时,您将参数传递为'keywords'所以将代码更改为

<script type="text/javascript">
$(document).ready(function () {
      $("#term").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "GetSubjectsName",
                data: { term: 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,
    });

});
</script>