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:
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:
using System.ComponentModel.DataAnnotations;
Step 3: Modify your code with the highlighted code below:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Vag_Infotech.Models
{
public class Student
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
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
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:
public int ID { get; set; }
[StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]
public string FirstName { get; set; }
[StringLength(20)]
public string LastName { get; set; }
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:
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:
using System.ComponentModel.DataAnnotations.Schema;
The code:
[StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]
[Column("First Name")]
public string FirstName { get; set; }
[StringLength(20)]
[Column("Last Name")]
public string LastName { get; set; }
Final Code for Student Entity
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Vag_Infotech.Models
{
public class Student
{
public int ID { get; set; }
[Required]
[StringLength(20, ErrorMessage="Your First Name can contain only 20 characters")]
[Display (Name="First Name")]
public string FirstName { get; set; }
[Required]
[StringLength(20, MinimumLength=2)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]
[Display(Name="Enrollment Date")]
public DateTime EnrollmentDate { get; set; }
public string Name
{
get { return FirstName + "," + LastName; }
}
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
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.