2016-03-21 86 views
1

我正在嘗試爲我的頁面創建自動完成功能。 我有一個文本框,我想從我的數據庫提出建議。使用JSON自動完成ASP.NET MVC

我有這個JsonResult在我的控制器:

public JsonResult ItemAutocomplete(string term) 
{ 
    var result = _db.SelectTable("SELECT [i].[Name] from [dbo].[Item][i] WHERE [i].[Name] LIKE @0", SqlDb.Params(term +"%")); 
    return Json(result, JsonRequestBehavior.AllowGet); 
} 

在我看來:

@Scripts.Render("~/bundles/jqueryui") 
<h2>jQuery AutoComplete</h2> 
<script> 
     $(function() { 
      $('#tags').autocomplete({ 
       source: function (request, response) { 
        $.ajax({ 
         url: '@Url.Action("ItemAutocomplete")', 
         extraParams: { term: $('#tags').val(), 
         dataType: "json", 
         contentType: 'application/json, charset=utf-8', 
         data: { 
          term: $("#tags").val() 
         }, 
         success: function (data) { 

          response($.map(data, function (item) { 
           return { 
            label: item 
           }; 
          })); 
         }, 
         error: function (xhr, status, error) { 
          alert(error); 
         } 
        }); 
       }, 
       minLength: 2 
      }); 
     }); 

</script> 

<div class="ui-widget"> 
    <label for="tags">Tags: </label> 
    <input id="tags" /> 
</div> 

的問題是,我ItemAutocomplete jsonResult總是收到一個空PARAM ......即使我打電話它直接從localhost,像這樣:「localhost/Appointment/ItemAutocomplete/item1」。

+0

我試過了,它也是這樣做的。我也收到這個錯誤:序列化'System.Reflection.RuntimeModule'類型的對象時檢測到循環引用。 –

+0

我懷疑SQL查詢。你有沒有在代碼隱藏中加入斷點?有什麼東西在_result_? – Bikee

+1

不確定是否導致此問題,但'extraParams:{term:$('#tags')。val(),'缺少關閉'}' –

回答

3

使用(request.term)以下

data: { term: request.term } 

,而不是

data: { term: $('#tags').val() } 

在自動填充文本框,搜索字符串由 「request.term」 檢測。

+0

它的工作原理,謝謝! :) –