I was with the same problem and did according to the code below
in the controller I made a method to return a search list in Json
public JsonResult BuscaNomePaciente(string text)
{
var list = PRep.Lista().Where(x => x.Nome.Contains(text)).Select(c =>
new { ID = c.ID, Nome = c.Nome });
return Json(list, JsonRequestBehavior.AllowGet);
}
In View Create this code snippet was implemented below:
//Referência das bibliotecas Jquery, Jequery ui
<link href="~/Content/themes/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery-ui.min.js"></script>
<div class="form-group">
@Html.LabelFor(model => model.Id_Paciente, htmlAttributes: new { @class
= "control-label" })
<input type="text" id="busca" class="form-control" placeholder="Busca
Paciente" />
<input type="text" id="hidden-Nome" name="Id_Paciente" />
</div>
<script>
$("#busca").autocomplete({
source: function (request, response) {
var text = $("#busca").val();
$.ajax({
type: "GET",
url: "/Paciente/BuscaNomePaciente",
dataType: "Json",
data: { text: $("#busca").val() },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Nome, value: item.ID }; // e
returned two values Name, and the ID of my control
}));
}
})
},
minLength: 2, // Busca a partir de 4 caractere digitado no campo
delay: 100,
select: function (event, ui) {
alert("ID do Nome Selecionado :" + ui.item.value)
$("#hidden-Nome").val(ui.item.value); // obtem o id da do Paciente
selecionada e adicioná-lo no input #hidden-Nome
}
});
</script>