title: How do Data Annotations work?
body: <p>I use Data Annotations in my ASP.NET MVC 3 project to validate the model. These are extremely convenient but currently they are magic to me. I read that data annotations do <em>not</em> throw exceptions. How then does MVC know to add validation errors to the model state dictionary? How does the failure to set a property on the model because of model validation bubble up to MVC if no exception is thrown? I always assumed that exceptions were thrown every time a property failed and that MVC model binding caught the exception and added it to the model state dictionary.</p>
  
  <p>To test this I created a console application and added a sample class with a validation annotation to it:</p>
  
  <pre><code>public class MyObject
  {
      [StringLength(10, MinimumLength=3)]
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I then instantiated the object and tried to assign values to the Name property that were less than 3. The property assigned just fine, despite the annotation that says string length of less than 3 is not allowed.</p>
  
  <pre><code>    static void Main(string[] args)
      {
          MyObject mine = new MyObject();
          mine.Name = "hi";
          Console.WriteLine(mine.Name);
          Console.ReadLine();
      }
  </code></pre>
  
  <p>This little program writes out "hi" to the console. Why? I was expecting it to get angry when trying to set <code>mine.Name</code> to "hi".</p>
  
  <p>What am I missing?</p>
  
  <p>Thanks in advance.</p>