MVC:文本框自动填充不起作用

时间:2015-10-07 11:37:31

标签: c# jquery asp.net-mvc model-view-controller

我正在尝试在特定文本框上实现自动填充,但到目前为止它还没有工作。这是我的代码。我错过了什么?

查看:

  <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”)

1 个答案:

答案 0 :(得分: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

感谢您回答我的问题。