Hi rani,
Check this example. Now please take its reference and correct your code.
For Entity Framework configuration refer below article.
For Ajax call refer below article.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult CheckName(string name)
{
Customer customer = Context.Customers.Where(x => x.ContactName == name).FirstOrDefault();
bool isExist = false;
if (customer != null)
{
isExist = true;
}
return Json(isExist);
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Name:
<input id="txtName" type="text" /><br /><span id="message"></span><br /><br />
<input type="button" value="Save" id="btnSave" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#btnSave').on('click', function () {
$.ajax({
type: "POST",
url: "/Home/CheckName",
data: '{name: "' + $("#txtName").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Name already exist.");
}
else {
message.html("");
}
}
});
});
});
</script>
</body>
</html>
Screenshot