通过Json在MVC4中实现自动完成文本框

时间:2014-07-21 14:28:09

标签: jquery json autocomplete

我想在文本框中实现自动填充功能。下面是一个获取用户输入的字符串的方法。在选择了唯一数据后,我想保存ID&值也在数据库中,但我不知道如何处理这个只返回Value为JSON的代码。

public ActionResult BrokerSearch(string broker) {
    //Get BrokerName from database

    var drpList = HelperClass.GetBrokerDropDownValues("brokerCompanyName");
    //var dlist = drpList.ToList().Find(x => x.DropDownListValue.Contains(broker));
    //List<String> arr = drpList.Select(c =>  c.DropDownListValue.ToString()).ToList();
    List < String > arr = drpList.Select(c = > new {
        c.DropDownListValue, c.DropDownListId
    }.ToString()).ToList();

    return Json(arr.Where(t = > t.StartsWith(broker)), JsonRequestBehavior.AllowGet);

}

我的Javascript如下:

  $("#brokerCompanyName").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: baseurl + "/Policy/BrokerSearch",
            type: "POST",
            dataType: "json",
            data: {
                broker: request.term
            },
            success: function (data) {
                if (data != null && data != '') {
                    response($.map(data, function (item) {
                        return {
                            label: item,
                            value: item
                        };
                    }))

                } else {
                    $('ul[class*=ui-autocomplete]').hide();
                }
            }
        })
    },
    minLength: 1,
    cache: false,
    select: function (event, ui) {
        if (ui != null && ui.item != null) {

            $("#brokerCompanyName").val(ui.item.value);
        }
    }
});

1 个答案:

答案 0 :(得分:-1)

<script>
    $(function () {
        $("#brokerCompanyName").autocomplete({

            source: function (request, response) {

                $.ajax({
                    url: "/Policy/BrokerSearch",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Text, value: item.Value };
                        }))
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    });

</script>