TOC

The community is working on translating this tutorial into Arabic, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Models:

DataAnnotations

In the previous article, we started digging into the very relevant subject of Model Binding. With Model Binding, we can create a stronger connection between the Model and the View and in return, we get a lot of help in the creation of markup and processing of requests. The View simply "reads" your Model (class) and then uses the available information to help you, e.g. by creating a relevant text box control for a property in a form.

However, sometimes it can be relevant for your Views to know more about a property on your Model than just its name and type. For these situations, ASP.NET MVC comes with the concept of DataAnnotations (sometimes referred to as Model Attributes), which basically allows you to add meta data to a property. The cool thing about DataAnnotations is that they don't disturb the use of your Models outside of the MVC framework.

How to use DataAnnotations

Allow me to give you a quick idea of how DataAnnotations work. For instance, a very common scenario, which we actually saw in the previous article, is that we would like to have the framework generate a label and an input field for a property. When generating the label, the name of the property is used, but property names are generally not nice to look at for humans. As an example of that, we might want to change the display-version of the FirstName property to "First Name". With DataAnnotations, that's very easy:

public class WebUser
{
    [Display(Name="First Name")]
    public string FirstName { get; set; }
}

Notice how the DataAnnotation just sits on top of the property, just like any other type of C# Custom Attribute. Using the Display DataAnnotiation, we can alter the display version of the property name. With that in place, our property keeps its original name, but whenever it's presented to a user, an alternate version of "First Name" is used.

Types of DataAnnotations

This was just an example of one of the many available DataAnnotation attributes. There are many more, but a lot of them relates directly to validation, a subject which we'll be discussing in one of the next articles. But for a complete list of available annotation attributes, I suggest that you check out the documentation.

Summary

DataAnnotations allow you to enrich your Models with meta data, which can be used for a wide range of purposes by the MVC framework. We'll talk about one of the most important use-cases for DataAnnotations in the next article: Model Validation.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!