2016-03-21 91 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

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