Data Annotation Basics

suggest change

Data annotations are a way of adding more contextual information to classes or members of a class. There are three main categories of annotations:

Usage

Here is an example where two ValidationAttribute and one DisplayAttribute are used:

class Kid
{
    [Range(0, 18)] // The age cannot be over 18 and cannot be negative
    public int Age { get; set; }
    [StringLength(MaximumLength = 50, MinimumLength = 3)] // The name cannot be under 3 chars or more than 50 chars
    public string Name { get; set; }
    [DataType(DataType.Date)] // The birthday will be displayed as a date only (without the time)
    public DateTime Birthday { get; set; }
}

Data annotations are mostly used in frameworks such as ASP.NET. For example, in ASP.NET MVC, when a model is received by a controller method, ModelState.IsValid() can be used to tell if the received model respects all its ValidationAttribute. DisplayAttribute is also used in ASP.NET MVC to determine how to display values on a web page.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Data Annotation:
* Data Annotation Basics

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
50 Data Annotation
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script