Asp .Net MVC Validation Process Using Data Annotation
Asp .Net MVC Validation Process Using Data Annotation
NET MVC
There are various ASP.NET Development company who posses ample of expertise and high
proficiency skills in ASP.NET Development sector. But to be one of the most renowned ASP.NET
development company, it's necessary for every employer to focus on hiring an eventually
sound.NET developer who will bring out the maximum and best output to you.
using System.ComponentModel.DataAnnotations;
namespace MvcApplication.Model
{
public class Employee
{
public int EmployeeId { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
[Required]
public string AboutMe { get; set; }
[Display(Name = "Employee Salary")]
[Required]
[RegularExpression(@"^\$?\d+(\.(\d{2}))?$",ErrorMessage="Employee
Salary must be a decimal value")]
public decimal Salary { get; set; }
}
}
# List 1:
The Employee class deals with coding guides, user about how to use additional attribute: the
Display attribute. The Display attributes allows you to modify the property name at the time
property is displayed as an error message. Employee class in Listing 1 with Create () controller
action feature in Listing 2 can easily be used together. This controller action will again display the
Create view property at the time when a model state will contain errors.
using System.Web.Mvc;
using MvcApplication.Models;
namespace MvcApplication.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Employee/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "EmployeeId")]Employee
employeModel)
{
if (!ModelState.IsValid)
return View();
// TODO: Add insert logic here
return RedirectToAction("Index");
}
}
}
# List 2: Controllers\EmployeeController.cs
Create the view feature in Listing 3 by simply right-clicking on Create() action and then select the
menu option known as Add View. Create a view with the Employee class as a model class. Again
select Create option from the view content dropdown list.
@model MvcApplication.Models.Employee
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.AboutMe, new { @class = "controllabel col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.AboutMe)
@Html.ValidationMessageFor(model => model.AboutMe)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Salary, new { @class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary)
@Html.ValidationMessageFor(model => model.Salary)
</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")
}
# List 3: Views\Employee\Create.cshtml
At the time of submitting a form to create any Employee, if you do not enter the specific values
for all the required fields, then the validation error messages in Figure 3 will be displayed.
If you enter an invalid value in Salary, then the error message in Figure 4 is displayed.
# Steps To Work With Data Annotation Validators with the Entity Framework
If you are working with the Microsoft Entity Framework to validate a data model class, then it's not
possible to apply validator attributes directly to classes. The reason behind this: Entity Framework
Designer generates various model classes, and any modifications that are made to the model class
will be overwritten next time if you come across with any changes in the Designer.
To use validators with classes that are generated by the Entity Framework with ASP.NET MVC,
then it's necessary to create metadata classes first. Apply validates to your metadata class.
# Figure 5: State class generated by Entity Framework
using System.ComponentModel.DataAnnotations;
namespace MvcApplication.Model
{
[MetadataType(typeof(StateMetaData))]
public partial class State
{
}
public class StateMetaData
{
[Required]
[Display(Name="State Name")]
public object StateName { get; set; }
}
}
# Listing 4: Models\State.cs
The file in Listing 4 comprises of two classes that are known as State class and
StateMetaData class. Here State class is a partial class that easily corresponds to the partial
class at the time time it is generated by Entity Framework, contained in the DataModel.Designer.vb
file.
Note: But currently .NET framework does not support partial properties.
Here State partial class is developed with MetadataType attribute that signifies the
StateMetaData class. StateMetaData class comes with proxy setting properties for State
class property.
The page in Figure 6 illustrates the error messages returned when you enter invalid values for the
State properties.
To work with ASP.NET MVC Data Annotations, it is necessary to hire a highly experienced
Asp .NET Developer who possesses high.NET coding skills.