title: Adding mvc model validation attributes in runtime
body: <p>I have an domain entity, Person, which has dynamic properties stored in a Dictionary</p>
  
  <p>Each property has a Name, Value and can be of different types (enum) [Email,Number etc] a property can also be required.</p>
  
  <p>These properties are mapped to a PropertyViewModel when rendered with corresponding html controls based on the property type.</p>
  
  <p>I would also like to add the DataAnnotaions validation attributes Required, Email etc and use builtin validation both client/server at runtime when the properties are mapped to PropertyViewModels</p>
  
  <p>Ive struggled some with TypeDescriptor.AddAttribute but I cant get it to work. Does anyone had any luck with this scenario?</p>
  
  <p><strong>Edit</strong>:
  I've finally got a combination of TypeDescriptor and custom ModelValidatorProver to work.
  Since I use validation attributes on all other viewmodels and didnt wanta mix of validation patterns I didnt want to make a custom modelvalidator that adds attributes by propertyname and type.</p>
  
  <p>Before rendering my viewmodel I decorate the properties with TypeDescriptor
      TypeDescriptor.AddAttributes(propertyViewModel.Value, new EmailAttribute());
      TypeDescriptor.AddAttributes(propertyViewModel.Value, new RequiredAttribute());</p>
  
  <p>And since the MVC default DataAnnotationsModelValidatorProvider doesnt support TypeDescriptor added attributes. I created a custom ModelValidation provider that uses TypeDescriptor to find the validation attributes.</p>
  
  <pre><code>public class TypeDescriptorModelValidationProvider : DataAnnotationsModelValidatorProvider
  {
      protected override IEnumerable&lt;ModelValidator&gt; GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable&lt;Attribute&gt; attributes)
      {
  
          var attributesList = new List&lt;Attribute&gt;(TypeDescriptor.GetAttributes(metadata.Model).Cast&lt;Attribute&gt;());
  
  
          return base.GetValidators(metadata, context, attributesList);
      }
  }
  </code></pre>
  
  <p>Which I replace the current with at startup</p>
  
  <pre><code>ModelValidatorProviders.Providers.Clear();
  ModelValidatorProviders.Providers.Add(new TypeDescriptorModelValidationProvider());
  </code></pre>