Hi rani,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
For configuring Entity framework refer below article.
ASP.Net Core: Simple Entity Framework Tutorial with example
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AutoComplete([FromBody]Auto auto)
{
var customers = (from customer in this.Context.Customers
where customer.ContactName.StartsWith(auto.prefix)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return Json(customers);
}
public class Auto
{
public string prefix { get; set; }
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$("#txtCustomer").autocomplete({
source: function (request, response) {
var myData = { "prefix": request.term };
$.ajax({
url: '/Home/AutoComplete/',
data: JSON.stringify(myData),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
</head>
<body>
Name: <input type="text" id="txtCustomer" />
</body>
</html>
Screenshot