Model Base validations:
ASP.NET
MVC uses DataAnnotations attributes to implement validations. We can apply to
the properties of model class.
Validation
we can perform in model class by using namespace called as System.ComponentModel.DataAnnotations.
Required means value of the property must be provided
[Required(ErrorMessage ="Please Enter Employee Name")]
public string EmpName { get; set; }
Display: This attribute is used to display the property name.
[Display(Name ="Employee Name")]
public string EmpName { get; set; }
Compare: its means compare between password and conformPassword properties.
public string Password { get; set; }
[Compare("Password")]
public string ConformPassword { get; set; }
DataType: This attribute specifies the type of the property like Email
[DataType(DataType.EmailAddress,ErrorMessage ="InValid Email Address")]
public string EmailId { get; set; }
Range: this validation we can use for specifies the min to max value for property.
[Range(18,40,ErrorMessage ="Age should be between 18-40")]
public int Age { get; set; }
StringLength: this validation we can use how many numbers of characters are allowed for that particular property.
[StringLength(10,ErrorMessage ="Address should be 10 char long")]
public string Address { get; set; }
Remote Attribute:
It is an attribute for validation in Data Annotation, which is used in model class validate the record instantly.
It is used to call sum ajax calls. If validation
is true then display and if validation is false it’s display error message.
First parameter Second parameter Third parameter
[Remote("IsUserNameValid","EmployeeModel", ErrorMessage = "Employee Name Already Exists.")]
public string EmpName { get; set; }
First parameter is Action name.
Second parameter is a Controller name
Third parameter is Error message
In above Remote attribute validation line like below
IsUserNameValid:
This is the JsonResult method which checks the details from database and returns true or false.
EmployeeModel:
This is MVC Controller name and inside that, IsUserNameValid JsonResult method is defined to check the details from database.
ErrorMessage :
This is used to show the error message.
Right
click on model folder -> Add -> Class -> name(EmployeeModel.cs) ->
Add
using
System;
using
System.Collections.Generic;
using
System.ComponentModel.DataAnnotations;
using
System.Linq;
using
System.Web;
namespace
WebApplication.Models
{
public class EmployeeModel
{
[Key]
public int EmpId
{ get; set; }
[Required(ErrorMessage ="Please
Enter Employee Name")]
[Display(Name ="Employee
Name")]
[Remote("IsUserNameValid","EmployeeModel", ErrorMessage
= "Employee Name Already Exists.")]
public string
EmpName { get; set; }
[Required(ErrorMessage = "Please
Enter Password")]
public string
Password { get; set; }
[Compare("Password")]
public string
ConformPassword { get; set; }
[DataType(DataType.EmailAddress,ErrorMessage
="InValid Email Address")]
public string
EmailId { get; set; }
[Range(18,40,ErrorMessage ="Age
should be between 18-40")]
public int Age { get; set; }
[StringLength(10,ErrorMessage ="Address
should be 10 char long")]
public string
Address { get; set; }
}
}
when you apply validation in model it will display in View page.
Right click on
controller-> Add -> Controller -> Name (EmployeeController.cs) page ->
Add
public
ActionResult Validations()
{
return
View();
}
public JsonResult IsUserNameValid(string EmpName)
{
if(EmpName == "supriya")
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
public JsonResult IsUserNameValid(string EmpName)
{
if(EmpName == "supriya")
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Right click on Validations
method in Controller -> Add View
Select like above and
click Add button. Its created Validations.cshtml page like below
@model WebApplication.Models.EmployeeModel
@{
ViewBag.Title = "Validations";
}
<h2>Validations</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>EmployeeModel</h4>
<hr />
@Html.ValidationSummary(true, "", new {
@class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.EmpName,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmpName, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.EmpName, "", 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.ConformPassword,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ConformPassword,
new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.ConformPassword, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EmailId,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmailId, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.EmailId, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Address,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>
model.Address, "", 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>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
when you build the application the output shown like below
Incase the validationsummary its give false, it's shows all required validation in above the fields like below
@Html.ValidationSummary(false, "", new { @class = "text-danger" }
AntiForgeryToken: it’s created a hidden key for form, that is valid till the form is submitted. Very time its create new key for form.
@Html.ValidationSummary(false, "", new { @class = "text-danger" }
AntiForgeryToken: it’s created a hidden key for form, that is valid till the form is submitted. Very time its create new key for form.
EditorFor: it is Html helper class to create a control base of the particular
model
ValidationSummary to display all the error
messages in the view.
ValidationMessageFor helper method to display field
level error messages in the view.
Scaffolding Column:
It is used to hide property
in UI, if it is EditorForModel and DisplayForModel.
First, we create method
in HomeController.cs page like below:
public
ActionResult Disply()
{
return
View();
}
Add view for display
method and copy below code
@model WebApplication.Models.EmployeeModel
@{
ViewBag.Title = "Disply";
}
<h2>Disply</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
When
you run the application, it shows output like below:
Add
below code in beginform method in display view
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel("EmployeeModel")
}
In above screen I don’t want to
display EmpId so, we go and change in EmployeeModel.cs page
In EmployeeModel.cs page I don’t want
to delete EmpId but, I want to hide things in model class.
[ScaffoldColumn(false)]
public int EmpId
{ get; set; }
No comments:
Post a Comment