没有插件的MVC3和Twitter Bootstrap TypeAhead

时间:2013-02-05 18:46:54

标签: asp.net-mvc-3 entity-framework twitter-bootstrap typeahead

我已经让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没有显示任何内容。

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

1 个答案:

答案 0 :(得分: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
        };