Performing Data Annotation in ASP.Net MVC 5

Introduction

This article will introduce you to DataAnnotation in MVC 5. In the previous article Perform CRUD Functionality we created some data for the Student entity but in the EnrollmentDate column the date comes with the time. The time is by default 12:00 AM. You can see that in the following screenshot:

 Page in MVC

Now, in that context we will validate the date time and other data type values for storing the right value and displaying the date without time or with the correct time. We can use the attributes for specifying the formatting, validation and database mapping rules. We can validate the date value in which the time is displayed along with the date and for that we need to make one code change that will fix it. So now let's proceed with the following sections:

  • DataAnnotation with DataType Attribute
  • DataAnnotation with StringLength Attribute
  • DataAnnotation with Column Attribute

DataAnnotation with DataType Attribute

We can validate the date value in which the time is displayed along with the date and for that we need to make one code change that will fix it. Use the following procedure to do that.

Step 1: Open the Models\Student.cs file.

Step 2: Add the following reference:

  1. using System.ComponentModel.DataAnnotations; 

Step 3: Modify your code with the highlighted code below:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4.   
  5. namespace Vag_Infotech.Models  
  6. {  
  7.     public class Student  
  8.     {  
  9.         public int ID { getset; }  
  10.         public string FirstName { getset; }  
  11.         public string LastName { getset; }  
  12.         [DataType(DataType.Date)]  
  13.         [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]  
  14.         public DateTime EnrollmentDate { getset; }  
  15.   
  16.         public virtual ICollection<Enrollment> Enrollments { getset; }  
  17.     }  
  18. } 

In the code above, you can see that we have applied the DataType DataAnnotation for the EnrollmentDate property of the Student entity. In this case you can see that we only want to show the date, not the full date and time. This DataType Enumeration provides many types of data types, like Date, Time, Currency, Email and so on. We can also enable the type-specific features that are automatically provided by the application. ApplyFormatInEditMode specifies that the specified formatting should also be applied when the value is displayed in a text box for editing.

Step 4: Now run the application and open the Students link

Validation in Mvc Page

You can see in the preceding screenshot that the time is no longer displayed for the dates. It is applicable for every view that will use the Student entity.

DataAnnotation with StringLength Attribute

The StringLength attribute is used to apply the maximum length of the string and used to provide the client-side and server-side validation for the ASP.NET MVC application. The attributes are also used to provide the rules and error messages.

In that context, in your Student.cs file apply the following code with the highlighted text:

  1. public int ID { getset; }  
  2. [StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]  
  3. public string FirstName { getset; }  
  4. [StringLength(20)]  
  5. public string LastName { getset; } 

In the code above, you can see that the FirstName property has the StringLength attribute and in it we've applied that this can contain only 20 characters.

If you run the application and click on the Students link then you'll get error like:

"The model backing the CollegeDbContext context has changed since the database was created.Consider using Code First Migrations to update the database"

So, go to the Package Manager Console and write the following command:

add-migration MaxLengthOnNames

update-database

Now, run the application and open the Students link:

Create Page in Mvc

DataAnnotation with Column Attribute

Now in this case we'll see how to use the attribute to change the column name and show the appropriate column name. Suppose we have the property named "FirstName" but you want that the name is to be the First Name, then this attribute is useful.

This attribute specifies that when the database is created, the column of the Student table that maps to the FirstName property will be named First Name.

So, let's proceed with the following procedure.

Step 1: Open the Student.cs file.

Step 2: Modify your code with the highlighted code below.

At first add the following reference:

  1. using System.ComponentModel.DataAnnotations.Schema; 

The code:

  1. [StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]  
  2. [Column("First Name")]  
  3. public string FirstName { getset; }  
  4. [StringLength(20)]  
  5. [Column("Last Name")]  
  6. public string LastName { getset; } 

Final Code for Student Entity

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5.   
  6. namespace Vag_Infotech.Models  
  7. {  
  8.     public class Student  
  9.     {  
  10.         public int ID { getset; }  
  11.         [Required]  
  12.         [StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]  
  13.         [Display (Name="First Name")]  
  14.         public string FirstName { getset; }  
  15.         [Required]  
  16.         [StringLength(20, MinimumLength=2)]  
  17.         [Display(Name = "Last Name")]  
  18.         public string LastName { getset; }  
  19.         [DataType(DataType.Date)]  
  20.         [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]  
  21.         [Display(Name="Enrollment Date")]  
  22.         public DateTime EnrollmentDate { getset; }  
  23.   
  24.         public string Name  
  25.         {  
  26.             get { return FirstName + "," + LastName; }  
  27.         }  
  28.         public virtual ICollection<Enrollment> Enrollments { getset; }  
  29.     }  
  30. } 

In the code above, we've applied the Required attribute for the columns that are required for the database. This attribute is not needed for the value types, such as int, double and DateTime. The value type fields are by default as required fields because they cannot have the null value. The Display attribute is used to specify the caption for the text boxes.

Summary

This article will help you to create and apply the DataAnnotation with various attributes. You can also learn to apply the migration for the changes in the database. Thanks for reading.


Similar Articles