TOC

This article is currently in the process of being translated into Vietnamese (~37% done).

Models:

DataAnnotations

Trong các bài trước, chúng ta đã tìm hiểu qua về Model Binding. Với Model Binding, ta có thể tạo ra kết nối giữa Model và View. View chỉ đọc Model và sau đó dùng thông tin sẵn có để tạo ra các text box trong 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; }
}

Chú ý DataAnnotation ở trên của khai báo property, giống các loại thuộc tính khác trong C ". Dùng Display để có thể thay đổi hiển thị tên các thuộc tính. Như vậy thuộc tính có thể giữ lại tên nhưng hiển thị theo cách khác cho người dùng, phía người dùng sẽ là "First Name".

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

DataAnnotation được sử dụng cho nhiều mục đích trong MVC. Chúng ta sẽ nói về một ứng dụng của DataAnnotation trong bài tới đó là: Kiểm tra tính hợp lệ của Model.


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!