JQuery - use a key / value pair in autocomplete

In my ASP MVC view, I pass the key / value pair back from the controller. Looking at the violinist and viewing in the Chrome debugger, I see that the information is being transferred correctly.

I would like the value key / value pair to be the element that appears in the autocomplete list. When the user selects an item from the list, I would like this key element to be placed in the text box.

Here is the jQuery code from my view

 $(function () { $('#DRMCompanyId').autocomplete({ source: '@Url.Action("compSearch", "AgentTransmission")', minLength: 2, select: function (event, ui) { $('#DRMCompanyId').val(ui.item.label); } }); }); 

One thing that I noticed is that if I add the ui variable to the watch list in the browser debugger, I notice that the label and value are the same. Again, however, I see that the return is a full key / value pair.

The following is a screenshot of the Network / Response console after the search is completed. Some of the data is private, so I darkened it, however you can see that a key / value pair is being returned.

enter image description here

+6
source share
2 answers

You need to make an AJAX request yourself and convert 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 }); }); 

In addition, the value property of an autocomplete element is automatically placed in input when this element is selected, so there is no need for a special select handler.

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

+13
source

Same top bit designed

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> 

FROM#

 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

enter image description here

0
source

Source: https://habr.com/ru/post/925771/


All Articles