Hi trisetia302,
Use the model as your parameter with FromBody attribute.
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
Model
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { 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 SearchName([FromBody] Customer prefix)
{
var customers = (from customer in this.Context.Customers
where customer.ContactName.StartsWith(prefix.ContactName)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return Json(customers);
}
}
View
@model Core_MVC_AutoComplete.Models.Customer
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript">
$(function () {
$("[id*=ContactName]").autocomplete({
source: function (request, response) {
var prefix = { ContactName: request.term};
$.ajax({
url: '@Url.Action("SearchName", "Home")',
data: JSON.stringify(prefix),
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) {
$("#CustomerID").val(i.item.val);
},
minLength: 1
});
});
</script>
<form>
<div class="row">
<div class="col-md-6">
<div class="position-relative form-group">
<label asp-for="CustomerID" class="control-label"></label>
<input asp-for="CustomerID" name="CustomerID" id="CustomerID" class="form-control" required />
</div>
<span asp-validation-for="CustomerID" class="text-danger"></span>
</div>
<div class="col-md-6">
<div class="position-relative form-group">
<label asp-for="ContactName" class="control-label"></label>
<input asp-for="ContactName" name="ContactName" id="ContactName" class="form-control" />
<span asp-validation-for="ContactName" class="text-danger"></span>
</div>
</div>
</div>
</form>
</body>
</html>
Screenshot