In Razor view ====== \home\form ==/views/home/form.cshtml
@using (Html.BeginForm("form", "Home", FormMethod.Post)) {
<div>
@Html.TextBoxFor(m => m.FirstName, new { @id = "FirstName", @placeholder = "Firstname", @onblur = "onc();" })
@Html.ValidationMessageFor(m => m.FirstName, string.Empty) <br />
<script>
onc = (function () {
var fn = $('#FirstName').val();
$.ajax({
url: '@Url.Action("CheckName", "Home")',
type: 'POST',
data: { Text: fn }
})
.done(function () {
// $("#refTable").html(partialViewResult);
});
});
</script>
</div>}
In Controller ====== HomeController.cs
public ActionResult form()
{
return View();
}
[HttpPost]
public ActionResult CheckName(string Text)
{
string output = string.Empty;
testEntities ws = new testEntities();
var e = ws.Employees.Where(em=>em.FirstName == Text);
if (e.Count()>0)
{
output = "no";
}
else
output = "null";
return Json(output, JsonRequestBehavior.AllowGet);
}
=after verify=====
if (ModelState.IsValid) { //check whether name is already exists in the database or not bool nameAlreadyExists = * check database * if(nameAlreadyExists) { ModelState.AddModelError(string.Empty, "Student Name already exists."); return View(std); } }
http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary