Hello. There is a form filling functionality. Everything is working. After filling the field and sending it to the server, I need the Voyager
method to accept the Id
my models, not the names. If {value = a.Id, label = a.Name}
. This leads to the fact that the list of names is displayed in the drop-down list, and when selected - Id.
HTML
<div class="container"> <div class="row"> <h2>Выбор маршрута</h2> @using (Html.BeginForm("Index", "Voyager", FormMethod.Post, new { @class = "navbar-form" })) { <div class="form-group"> <input type="text" name="nameBusStopStart" class="form-control" placeholder="Начальный пункт" data-autocomplete-source='@Url.Action("AutocompleteBusStopStart", "Main")'> </div> <button type="submit" class="btn btn-success">Submit</button> } </div>
Model
public class BusStopViewModel { public int Id { get; set; } public string Name { get; set; } }
Controller
public ActionResult AutocompleteBusStopStart(string term) { var models = _busStopRepository.AutocompliteBusStopStartRepo(term).Select(a=>new{value = a.Name, label = a.Name, id = a.Id}); return Json(models, JsonRequestBehavior.AllowGet); }
AutocompliteBusStopStartRepo ()
public IQueryable<BusStop> AutocompliteBusStopStartRepo(string nameBusStop) { var names = db.BusStops.Where(p => p.Name.ToUpper().Contains(nameProduct.ToUpper())); return names; }
jquery-ui
$(function () { $("[data-autocomplete-source]").each(function () { var target = $(this); target.autocomplete({ source: target.attr("data-autocomplete-source"), minLength: 2 }); }); });