in this article, I will show remote validation in asp.net mvc
model :
public class User
{
public int Id { get; set; }
[Remote("IsUserExists", "Home", ErrorMessage = "User name already exist")]
[Required(ErrorMessage = "Please Enter User name.")]
public string Username { get; set; }
}
controller :
List<User> objusers = new List<User>()
{
new User {Username="Ajay",Id=1},
new User {Username="Sharavan",Id=2},
new User {Username="Dhruv",Id=3},
};
public JsonResult IsUserExists(string Username)
{
return Json(!objusers.Any(x => x.Username.ToLower() == Username.ToLower()), JsonRequestBehavior.AllowGet);
}
view :
@model RemoteValidation.Models.User
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<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>
0 Comments
if you have any doubts , please let me know