Hi Richa,
Check this example. Now please take its reference and correct your code.
For Entity Framework configuration 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
Model
public class Customer
{
[Key]
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 IActionResult Index(string name)
{
Customer customer = Context.Customers.Where(x => x.ContactName == name).FirstOrDefault();
if (customer != null)
{
ViewBag.Message = "Exist";
return View();
}
else
{
return View(customer);
}
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using Data_Exist_Core_MVC.Models;
@model Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post">
Name:
<input type="text" name="name" />
@if (ViewBag.Message != null && ViewBag.Message == "Exist")
{
<br /><span style="color:red;">Name already exist.</span>
}
<br /><br /><input type="submit" value="Save" />
</form>
</body>
</html>
Screenshot