Hi rani,
Using the below article i have created the example.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = (from customer in this.Context.Customers
where customer.ContactName.StartsWith(prefix == null ? "" : prefix)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return Json(customers);
}
[HttpPost]
public IActionResult Index(string CustomerName, string CustomerId)
{
ViewBag.Message = "CustomerName: " + CustomerName + " CustomerId: " + CustomerId;
return View();
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
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;
}
.ui-autocomplete {
overflow: auto;
max-height: 100px;
}
</style>
</head>
<body>
<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 href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#txtCustomer").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Home/AutoComplete/',
data: { "prefix": request.term },
type: "POST",
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) {
$("#hfCustomer").val(i.item.val);
},
minLength: 0
}).focus(function () {
$(this).autocomplete("search");
});
});
</script>
<form asp-action="Index" asp-controller="Home" method="post">
<input type="text" id="txtCustomer" name="CustomerName" />
<input type="hidden" id="hfCustomer" name="CustomerId" />
<br /><br />
<input type="submit" id="btnSubmit" value="Submit" />
<br /><br />
@ViewBag.Message
</form>
</body>
</html>
Screenshot