2015-10-07 17 views
0

我試圖在特定的文本框上實現自動填充,但目前爲止還沒有工作。這是我的代碼。我錯過了什麼?MVC:Textbox autopopulate無法正常工作

VIEW:

<script type="text/javascript"> 
     $(document).ready(function() { 
      $("#lead-organisation").autocomplete({ 
       source: function (request, response) { 
        $.ajax({ 
         url: "/Project/AutoCompleteOrganisation", 
         type: "POST", 
         dataType: "json", 
         data: { term: request.term }, 
         success: function (data) { 
          response($.map(data, function (item) { 
           return { label: item.Organisation, value: item.Organisation }; 
          })) 

         } 
        }) 
       }, 
       messages: { 
        noResults: "", results: "" 
       } 
      }); 
     }) 
    </script> 


     <div class="form-group"> 
      <label for="@Html.IdFor(x => x.Organisation)"> 
       @Html.DisplayNameFor(x => x.Organisation) 
      </label> 
      @Html.TextBoxFor(x => x.Organisation, new { @class = "form-control", data_project = "organisation", editorId="lead-organisation" }) 
      @Html.ValidationMessageFor(x => x.Organisation) 
     </div> 

我的控制器:

[AjaxOnly] 
    public ActionResult AutoCompleteOrganisation(string term) 
    { 
     var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>(); 
     var organisationList = new ProjectOrganisationModel(); 
     organisationList.Organisation = taxonomy.GetOrganisations(); 

     var result = from org in organisationList.Organisation 
        where org.Name.ToLower().Contains(term.ToLower()) 
        select org.Name; 

     return Json(result, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet); 
    } 

我也下載了這個:jquery.autocomplete.js並增加它在我的BundleConfig.cs .INCLUDE(「〜/腳本/jquery.autocomplete.js「)

+0

你得到任何控制檯錯誤? –

+0

你沒有帶id =「lead-organization」的元素(但是你有一個id =「Organization」') - 它需要是'$(「#Organization」)。autocomplete({ ...' –

+0

我使用的IE瀏覽器,並沒有錯誤彈出的JS。將使用FireBug嗎? – JADE

回答

0

我終於能夠工作了。

用這個代替:

<script type="text/javascript"> 
     $(document).ready(function() { 
      $("#lead-organisation").autocomplete({ 
       source: '@Url.Action("AutoCompleteOrganisation", "Project")' 
      }); 
     }) 
</script> 

對於控制器:

public JsonResult AutoCompleteOrganisation(string term) 
{ 
    var taxonomy = DependencyResolver.Current.GetService<TaxonomyHelper>(); 
    var organisationList = new ProjectOrganisationModel(); 
    organisationList.Organisation = taxonomy.GetOrganisations(); 

    var match = organisationList.Organisation.Where(x => x.Name.ToLower().Contains(term.ToLower())). 
     Select(e => e.Name).Distinct().ToList(); 

    return Json(match, JsonRequestBehavior.AllowGet); 
} 

然後我沒有下載任何自動完成插件,而不是隻用: jQuery的UI,1.10.4.custom.css jquery-ui-1.10.4.custom.js jquery-2.1.1.js

謝謝你回答我的問題。