Wednesday, November 28, 2012

How to implement data annotation in MVC Razor?


Validation  :

Validation is most important process for any of the application. This process prevents wrong input to the application. For generating the meaningful output it is must that input should be meaningful because based on input only application generates output.

Like other application we can also implement validation process for our MVC application also, in this article, I am explaining – How to implement validation using data annotation in MVC application.

To implement validation I have used Data annotation, for this first we need to use “System.ComponentModel.DataAnnotations” namespace in our application. Here I am giving step by step implementation.

Step1:

Create one simple MVC Application, for this open Visual Studio and select “New Project” option then select “Asp.Net MVC Application Template”.

After creating new application you will find default MVC folder structure.

Step2:

Now right click on “Models” folder and add one Class, I have added by named- “EmployeeModels.cs”.

Here I have declared some properties like this-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;  

namespace DataAnnotationArticle.Models
{
    public class EmployeeModels
    {
        public int ID { get; set; }
        

       //Validation for empty input
        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }



       //Validation for length of string
        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }
       
    }
}
 

As you can see that I have added reference of  “System.ComponentModel.DataAnnotations” Namespace which will help us to implement validation over data using data annotation.

For this I have set some validation over properties like this-

        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }

        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }


We have other properties also based on our need we can implement other validation.

Step3:

Now add one controller, for this right click on “Controller” folder and click on “Add Controller” option, I have added by named- “EmployeeController.cs”. I have written controller code like this-

public ActionResult EmployeeView()
        {
            return View();
        }


Now we have to bind this ActionResult with one View.

Step4

To bind this ActionResult with View, Just right click on “EmployeeView()“ and you will get menu list here click on “Add View …” option after that you will get one dialog, like this-


View


Fill the details here like I have given Now Finally say “OK”, then View will be created automatically with following lines of code-

@model DataAnnotationArticle.Models.EmployeeModels

@{
    ViewBag.Title = "EmployeeView";
}

<h2>EmployeeView</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>EmployeeModels</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FisrtName )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FisrtName )
            @Html.ValidationMessageFor(model => model.FisrtName )
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName )
            @Html.ValidationMessageFor(model => model.LastName )
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


Here we can see that, one user input form is generated with validation. This is because of “Create” option which we have set at the time of view creation.   For validating user input code is already written, this code will perform user validation based on this JavaScript files-

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


Finally our solution explorer structure will be like this-



MVC


Now you are done, to test the application just run your application and give some invalid input to the control like I have given , Here we can see the output-




MVCDataAnnotation



Here we can see that the validation which we have given in EmployeeModels.CS that is taking place for wrong input. Like this we can validation other controls also.




Thanks


No comments:

Post a Comment