Using DataAnnotations in MVC 2 - Catching up to Dynamic Data

 

UnexpectedError

DataAnnotations help you write robust validation and prevent the type of annoying error message shown above. Form submittal failure when a field doesn’t validate can be very frustrating -  especially when there is no indication of the problematic property or the constraint violation. I happened to get the Outlook error above when I attempted to submit a mail message to the MVC QA guys. It turns out the distribution list I made for them a few days earlier had problems.

The image below (From my sample while editing the Products table) provides much better feedback.

Validation

In my MSDN article How to: Validate Model Data Using DataAnnotations Attributes, I cover the basics of validation using the System.ComponentModel.DataAnnotations DLL.  DataAnnotations is not new to ASP.NET, Dynamic Data has been using it since v1, but it is new to MVC.

 

When Visual Studio 2010 is released, you’ll be able to use the richer .Net 4 DataAnnotations with MVC. DataAnnotations are a perfect fit to the MVC philosophy of SoC because data constraints are applied to the data model, not in the UI. The .Net 4 version of DataAnnotations adds 11 new attributes you can apply.