Remote attribute in asp.net MVC
What is Remote Attribute
- make a remote server call to validate specific data without posting the entire form to the server
- Remote is an attribute of data annotation
- Used for validation at model class in MVC.
- Implemented with the use of jquery, jquery.validate.min.js, jquery.validate.unobtrusive.
Note: Do not forget to add the following code at the view
<script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Example 1: Single model attribute validation
Step1: Create a database table (here table name is login in angular database)
CREATE TABLE [dbo].[login]( [id] [int] IDENTITY(1,1) NOT NULL, [username] [varchar](50) NULL, [password] [nvarchar](50) NULL, [lastlogin] [datetime] NULL ) ON [PRIMARY]
Step2: Create a Model and dbContext class using code first (if you are not aware with it, Please watch the video which is given below)
namespace testCode.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; using System.Web.Mvc; [Table("login")] public partial class login { public int id { get; set; } [StringLength(50)] [Remote("CheckUserName","RemoteValidationEx", ErrorMessage ="Username already exists")] public string username { get; set; } [StringLength(50)] public string password { get; set; } public DateTime? lastlogin { get; set; } } }
[Remote(“CheckUserName”,”RemoteValidationEx”, ErrorMessage =”Username already exists”)]
CheckUserName: It is JSON Action which will be defined in the controller to validate username is already exists or not, will return true or false.
RemoteValidationEx:Controller name where CheckUserName exists.
ErrorMessage: Which has to show as a validation error.
Step 3: Create a Controller class (RemoteValidationEx) and add the following code.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using testCode.Models; namespace testCode.Controllers { public class RemoteValidationExController : Controller { public ActionResult Index() { return View(); } public ActionResult Save() { return View(); } [HttpPost] public ActionResult Save(login obj) { using (var db = new Checkvalidation()) { if(ModelState.IsValid) { db.logins.Add(obj); return RedirectToAction("OK"); } return View(); } } public ActionResult OK() { return Content("OK"); } public JsonResult CheckUserName(string username) { using (var db = new Checkvalidation()) { var result = !db.logins.Any(x => x.username.ToLower() == username.ToLower()); return Json(result, JsonRequestBehavior.AllowGet); } } } }
@model testCode.Models.login @{ ViewBag.Title = "Save"; } <h2>Save</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>login</h4> <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"> @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.lastlogin, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.lastlogin, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.lastlogin, "", 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-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Step 3: Run your code and see the following URL.
http://localhost:50720/RemoteValidationEx/Save
(Note: localhost:50720 it will be changed as per your application port)
ASP.NET MVC Remote Validation For Multiple Fields With AdditionalFields Property
Step : 1 Change in Model Property of previous code (login.cs)
namespace testCode.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; using System.Web.Mvc; [Table("login")] public partial class login { public int id { get; set; } [StringLength(50)] public string username { get; set; } [StringLength(50)] [Remote("CheckUserName1", "RemoteValidationEx", AdditionalFields = "username", ErrorMessage = "Username already exists")] public string password { get; set; } public DateTime? lastlogin { get; set; } } }
Step 2: Change in controller
public JsonResult CheckUserName1(string username, string password) { using (var db = new Checkvalidation()) { var result = !db.logins.Any(x => x.username.ToLower() == username.ToLower() & x.password.ToLower() == password.ToLower()); return Json(result, JsonRequestBehavior.AllowGet); } }