Jquery autocomplete using mvc3 dropdown

I am using ASP.NET MVC3 with EF Code First. I have not worked with jQuery before. I would like to add an autocomplete function to the drop-down list attached to my model. An identifier is stored in the drop-down list and the value is displayed.

So, how to connect the Auto Complete widget for jQuery UI to display the value when the user types, but save the identifier?

I will need several autocomplete drop-down lists in one view.

I saw this plugin: http://harvesthq.github.com/chosen/ , but I'm not sure I want to add more "stuff" to my project. Is there a way to do this using jQuery UI?

+4
source share
3 answers

This is what I did FWIW.

$(document).ready(function () { $('#CustomerByName').autocomplete( { source: function (request, response) { $.ajax( { url: "/Cases/FindByName", type: "GET", dataType: "json", data: { searchText: request.term, maxResults: 10 }, contentType: "application/json; charset=utf-8", success: function (data) { response($.map(data, function (item) { return { label: item.CustomerName, value: item.CustomerName, id: item.CustomerID } }) ); }, }); }, select: function (event, ui) { $('#CustomerID').val(ui.item.id); }, minLength: 1 }); }); 

It works great!

0
source

Update

I just posted a sample project demonstrating jQueryUI autocomplete in a text box on GitHub https://github.com/alfalfastrange/jQueryAutocompleteSample


I use it with regular MVC TextBox like

 @Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", @class = "ui-widget TextField_220" }) 

Here's a clip of my Ajax call

First, it checks its internal cached file to find the element, if it does not find that it disables the Ajax request for my controller action to get comparable entries

 $("#SearchField").autocomplete({ source: function (request, response) { var term = request.term; if (term in entityCache) { response(entityCache[term]); return; } if (entitiesXhr != null) { entitiesXhr.abort(); } $.ajax({ url: actionUrl, data: request, type: "GET", contentType: "application/json; charset=utf-8", timeout: 10000, dataType: "json", success: function (data) { entityCache[term] = term; response($.map(data, function (item) { return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode }; })); } }); }, minLength: 3, select: function (event, result) { var id = result.item.id; var code = result.item.code; getEntityXhr(id, code); } }); 

This is not all the code, but you can see here how the cache is searched, then the Ajax call is made, and then what is done with the answer. I have a select section, so I can do something with the selected value

+3
source
-1
source

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


All Articles