Reputation: 643
For like few days I have been trying to make autocomplete in ASP.NET for my project. wherever I look their project are in .ashx or .aspx file, while mine is in cshtml. This is a work project so I cant change the file format. You might see how I have already asked this question in the past with my attempts but it doesn't work. I have seen few videos online which they use controllers but for some reason my project doesn't have controller for that part (_search). If anyone could give me hints or tip how to make easiest autocomplete which connects to database it would mean the world to me. Thanks in advance :D <3
Upvotes: 0
Views: 830
Reputation: 106
Well, you can try this Assuming you are searching country in controller.
public JsonResult SearchCountry(string query){
var dbResult=_context.Countries.Where(x=>x.Name.ToLower().StartWith(query.ToLower())).Take(20).ToList();
return Json(dbResult);
}
In CSHTML
<input type='text' id='autocomplete' >
Javascript:
$( "#autocomplete" ).autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url: "/demo/SearchCountry",
type: 'get',
data: {
query: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autocomplete').val(ui.item.name); // In MVC5 change name to Name
return false;
}
});
Upvotes: 2