0

我已经让 TypeAhead 可以正常处理静态数据,并且能够正确调用我的控制器函数并获取数据,但它要么是 A:没有正确解析数据,要么是 B:没有正确设置 TypeAhead。

JavaScript:

<input type="text" id="itemSearch" data-provide="typeahead" value="@ViewBag.Item" name="itemSearch"/>




    $('#itemSearch').typeahead({
    source: function (query, process) {
        parts = [];
        map = {};

        $.ajax({
                url: '@Url.Action("MakePartsArray")',
                dataType: "json",
                type: "POST",
                data: {query: query},
                success: function (data) {
                                $.each(data, function (i, part) {
                                map[part.description] = part;
                                parts.push(part.description);
                            });

                            typeahead.process(parts);
                }
            });
    },
    updater: function (item) {
        selectedPart = map[item].itemNumber;
        return item;
    },
    matcher: function (item) {
        if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
            return true;
        }
    },
    sorter: function (items) {
        return items.sort();
    },
    highlighter: function (item) {
        var regex = new RegExp('(' + this.query + ')', 'gi');
        return item.replace(regex, "<strong>$1</strong>");
    }
});

控制器 :

    public ActionResult MakePartsArray(string query)
    {
        var possibleItem = query.ToLower();
        var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
        return new JsonResult
        {
            ContentType = "text/plain",
            Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

在我的控制器中,我看到数据被正确检索,并且似乎可以正确解析,但我的 TypeAhead 没有显示任何内容。

关于如何准确验证故障发生位置的任何想法,或者是否有人在我的代码中看到直接错误?

4

1 回答 1

0

问题出在ajax调用中-

   $.ajax({
           url: '@Url.Action("MakePartsArray")',
           dataType: "json",
           type: "POST",
           data: {query: query},
           success: function (data) {
               $.each(data.matches, function (i, part) {
                   var composedInfo = part.description + ' (' + part.itemNumber + ')';
                   map[composedInfo] = part;
                   parts.push(composedInfo);
                });

                process(parts);
           }
       });

并在返回类型的控制器中

  return new JsonResult
        {
            ContentType = "application/json",
            Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
于 2013-04-01T18:09:29.303 回答