jQuery - Use key/value pair in autocomplete

后端 未结 2 1241
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 05:55

In my ASP MVC view, I am passing a key/value pair back from the controller. After looking at fiddler and viewing in Chrome\'s debugger I can see that the information is bein

相关标签:
2条回答
  • 2020-12-18 06:15

    Same from above, bit elaborated

    Front End

    <input id="CompanySearch" type="text" />
    
    <script>
        $(function () {
            $("#CompanySearch").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '@Url.Action("GetCompanyAutoComplete", "Admin")',
                        dataType: "json",
                        data: { term: request.term },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>
    

    C#

    public JsonResult GetCompanyAutoComplete(string term)
    {
        var search = term.Trim();
    
        var itemList = (from items in db.TblProductSuggestionFirsts where items.Name.StartsWith(search) select new { label = items.Name, value = items.Name }).Take(50).ToList();
    
        return Json(itemList, JsonRequestBehavior.AllowGet);
    
    }
    

    Json result format

    0 讨论(0)
  • 2020-12-18 06:29

    You'll need to make the AJAX request yourself and transform the data to the format that jQueryUI expects:

    $(function () {
        $('#DRMCompanyId').autocomplete({
            source: function (request, response) {
               $.ajax({
                   url: '@Url.Action("compSearch", "AgentTransmission")',
                   type: 'GET',
                   dataType: 'json',
                   data: request,
                   success: function (data) {
                       response($.map(data, function (value, key) { 
                            return {
                                label: value,
                                value: key
                            };
                       }));
                   }
               });
            },
            minLength: 2
        });
    });
    

    Also, the value property of an autocomplete item is automatically placed in the input when that item is selected, so there should be no need for a custom select handler.

    Example: http://jsfiddle.net/Aa5nK/60/

    0 讨论(0)
提交回复
热议问题