我试图实现一个特定的文本框上的自动填充,但它不工作到目前为止。这是我的代码。我错过了什么?
视图:
<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中其中包括(~/脚本/jquery.autocomplete.js)
我终于能让它工作了。
用这个代替:
<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.cssjquery-ui-1.10.4.custom.jsjquery-2.1.1.js
谢谢你回答我的问题。