Remote Attributes is used in Remote Validation
1. Model : Remote Validating is used on emp_name, Rirst fill the appropriate Action Method and Error message in the Remote Attribute
public class Employee
{
[Key]
public string emp_code { get; set; }
[Remote("checkEmpName", "Home", ErrorMessage = "User name already exists")]
public string emp_name { get; set; }
public string emp_mobile { get; set; }
}
2. Controller : Pass same property varibale name (emp_name) into Method checkEmpName
public class HomeController : Controller
{
public ActionResult Create()
{
return View();
}
public JsonResult checkEmpName(string emp_name)
{
List<Employee> list = new List<Employee>();
list.Add(new Employee { emp_code = "E001", emp_name = "Rinkesh", emp_mobile = "9027581975" });
list.Add(new Employee { emp_code = "E002", emp_name = "Rakesh", emp_mobile = "9027581975" });
list.Add(new Employee { emp_code = "E003", emp_name = "Ajay", emp_mobile = "9027581976" });
bool st = (!list.Any(x => x.emp_name == emp_name));
return Json(st, JsonRequestBehavior.AllowGet);
}
}
3. View : Required jquery is
jquery-3.3.1.min.js,
jquery.validate.min.js,
jquery.validate.unobtrusive.min.js
@model Angular1Test.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="row">
<div class="col-md-3">
@Html.LabelFor(model => model.emp_code, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.emp_code, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.emp_code, "", new { @class = "text-danger" })
</div>
<div class="col-md-3">
@Html.LabelFor(model => model.emp_name, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.emp_name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.emp_name, "", new { @class = "text-danger" })
</div>
<div class="col-md-3">
@Html.LabelFor(model => model.emp_mobile, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.emp_mobile, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.emp_mobile, "", new { @class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-12">
<br>
<input type="submit" value="Create" class="btn btn-default" />
@Html.ActionLink("Back to List", "Index", new { }, new { @class = "btn btn-default" })
</div>
</div>
}
<div>
</div>
</body>
</html>
A link to video
https://www.youtube.com/watch?v=DUej0Z8gDnA
No comments:
Post a Comment