Learn ASP.NET MVC Step By Step For Beginners - Part Three

Introduction

This session is the third part of the Learn ASP.NET MVC Step By Step for Beginners. I suggest reading the articles:

In this article, we will discuss,

What Are DataAnnotations?

How Do We Add Validations Using Model and DataAnnotations?

DataAnnotations

DataAnnotations use different attributes on our model to implement validations. DataAnnotations include built-in validation attributes for different validation rules, which can be applied to the properties of model class. The DataAnnotations attributes are included in System.ComponentModel. DataAnnotations namespace.

The following table lists DataAnnotations validation attributes.

DataAnnotations

Step 1 First of all, open a Visual Studio 2012

  1. File-> New-> Project.

    DataAnnotations

  2. Visual C#-> Web-> ASP.NET MVC 4 Web Application-> Name your project -> Ok.

    DataAnnotations

  3. From the New ASP.NET Project dialog, select MVC as shown below. And also select View Engine Razor.

    DataAnnotations

  4. Visual Studio creates the following folder structure for MVC application by default.

    DataAnnotations

Step 2 Add Student Model Class

  1. Right click on Model folder -> Add -> click on Class.

    DataAnnotations

  2. In the Add New Item dialog box, enter class name 'Student' and click Add.

    DataAnnotations

  3. This will add new Student class in model folder.

    DataAnnotations

  4. Add properties to Student Class Model as shown below.

    DataAnnotations

Step 3 apply DataAnnotation attribute on the properties of Student model class.

We want to validate that Student Name, Email, and Age is not blank. Name cannot more than 20 characters, Age should be between 18 and 50. Email is in a correct format.

  1. Add following Namespaces in Student Model Class.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4. using System.Linq;  
    5. using System.Web;  
  2. Apply DataAnnotation Attributes in Student Class as shown below.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel.DataAnnotations;  
    4. using System.Linq;  
    5. using System.Web;  
    6. namespace ValidationInModel.Models {  
    7.     public class Student {  
    8.         public int SId {  
    9.             get;  
    10.             set;  
    11.         }  
    12.         [Required(ErrorMessage = "name is required")]  
    13.         [StringLength(20, ErrorMessage = "name can not more than 20 characters")]  
    14.         public string name {  
    15.             get;  
    16.             set;  
    17.         }  
    18.         [Required(ErrorMessage = "Email is required")]  
    19.         [RegularExpression(@ "^([\w.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Email is not in a correct format")]  
    20.         public string mail {  
    21.             get;  
    22.             set;  
    23.         }  
    24.         [Required(ErrorMessage = "Age is required")]  
    25.         [Range(18, 30, ErrorMessage = "Age Should be Between 18 to 30")]  
    26.         public int age {  
    27.             get;  
    28.             set;  
    29.         }  
    30.     }  
    31. }  

Step 4 Adding New Controller

  1. Visual Studio, right click on the Controller folder -> select Add -> click on Controller.

    DataAnnotations

  2. It will open Add Controller dialog as shown below.

    DataAnnotations

  3. Write Controller Name. Do not delete the word Controller. Remember, controller name must end with Controller.

    DataAnnotations

  4. This will create HomeController class with Index method in HomeController.cs file under Controllers folder, as shown below.

    DataAnnotations

    Note Rebuild Project.

Step 5 Add View

  1. Open a HomeController class -> right click inside Index method -> click Add View.

    DataAnnotations

  2. In the Add View dialogue box, keep the view name as Index. It's good practice to keep the view name the same as the action method name so that you don't have to specify view name explicitly in the action method while returning the view.
  3. Select View Engine Razor.
  4. Create a Strongly typed view.
  5. Select Model Class

    DataAnnotations

  6. Add Code in View As Shown Below.
    1. @model ValidationInModel.Models.Student  
    2. @ {  
    3.     Layout = null;  
    4. } < !DOCTYPE html > < html > < head > < meta name = "viewport"  
    5. content = "width=device-width" / > < title > Index < /title> < /head> < body > < div > @using(Html.BeginForm()) { < p > Name @Html.TextBoxFor(m => m.name)  
    6.     @Html.ValidationMessageFor(m => m.name) < /p> < p > Mail @Html.TextBoxFor(m => m.mail)  
    7.     @Html.ValidationMessageFor(m => m.mail) < /p> < p > Age @Html.TextBoxFor(m => m.age)  
    8.     @Html.ValidationMessageFor(m => m.age) < /p> < p > < input type = "submit"  
    9.     value = "insert" / > < /p>  
    10. } < /div> < /body> < /html>  

Step 5 Create the POST Action Method in HomeController.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using ValidationInModel.Models; //add namespace of model here  
  7. namespace ValidationInModel.Controllers {  
  8.         public class HomeController Controller {  
  9.             public ActionResult Index() {  
  10.                     return View();  
  11.                 }  
  12.                 [HttpPost]  
  13.             public ActionResult Index(Student obj) {  
  14.                 return View();  
  15.             }  
  16.         }  
  17.     }  
  18.  
OUTPUT 1
DataAnnotations
OUTPUT 2

DataAnnotations

OUTPUT 3

DataAnnotations