I have a new project and decided to go with c# .net 6 MVC in VS2022…
In may old projects this code works flawless.
@section Scripts
{
<script type="text/javascript">
$("#Klijent_Name").autocomplete({
source: function (request, response) {
$.ajax({
url: "@Url.Action("SearchKlijenti")",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.label, id: item.id };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#KlijentId").val(ui.item.id);
$("#KlijentLabel").html(ui.item.label);
$("#SearchKupac").val("");
return false;
}
});
</script>
}
and latest variation of controller endpoint:
public JsonResult SearchKlijenti(string term)
{
var klijentVM = _klijent.Search(term);
if (klijentVM != null)
{
var items = klijentVM.Select(x => new { id = x.KlijentId, label = x.FriendlyName });
return new JsonResult(Ok(items));
}
return new JsonResult(Ok());
}
Using latest jQuery 3.6.1, and bootstrap 5.2.0. Tried using jquery-ui.js, jquery.unobtrusive-ajax.js…
Problem is that the call is not triggered, or not finding it’s way to controller action. Have tried putting alert(); and omitting data manipulation and calls, but still nothing. When testing jQuery:
$("SearchKupac").keyup(function() {
alert();
});
works.
Tried to debug using Firefox, but either I don’t know to use it, or the call is not triggered.
I don’t know where and what to look anymore…
EDIT: Here is also HTML snippet
<label asp-for="Klijent.Name">Ime</label>
<input class="form-control ajax" asp-for="Klijent.Name" />
<span asp-validation-for="Klijent.Name" class="text-danger"></span>
I also tried selecting with $("input.ajax")… Tried double and single quotes. Bare in mind, this is a working code from MVC 5 project. It doesn’t work in new project
2
Answers
So Firefox developer tool was of no help. Crome developer tool find an error. It was not apparent immediately, but the jquery-ui.js (of version 1.13.2 in my case) resolved the issue.
There was also an issue in controller. it has to be of type JsonResult and return Json(items) not Json(Ok(items))
And for completeness, here is my script:
}
Did not yet test return Json(null), but that is not part of this exercise :)
If you want to use keyup event,here is a demo:
js:
If the id of input is
SearchKupac
,you need to use$("#SearchKupac")
in js.Also,you can use$("#SearchKupac")
with autocomplete.