0

我已經獲得了TypeAhead與靜態數據正常工作,並且能夠正確調用我的控制器功能並獲取數據,但它是A:不正確解析數據或B:TypeAhead不是正確設置。MVC3和Twitter Bootstrap 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 
     }; 
    } 

在我控制我看到被正確檢索到的數據,它似乎正確地解析,但沒有被顯示出來了我的預輸入。

任何想法如何驗證故障發生的確切位置或有人看到我的代碼中的直接錯誤?

回答

0

問題是在阿賈克斯呼叫 -

$.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 
     }; 
+0

您可以在Ajax調用闡述問題的控制器? –

+0

成功之後,我沒有正確處理返回的Json。如果你在問題的代碼頂部插入答案,它應該可以工作。實際上,您還需要定義一個變量'selectedPart'來引用您選擇的任何內容,並在輸入框中刪除value ='@ViewBag.Item'。 –