0

I have an domain entity, Person, which has dynamic properties stored in a Dictionary

Each property has a Name, Value and can be of different types (enum) [Email,Number etc] a property can also be required.

These properties are mapped to a PropertyViewModel when rendered with corresponding html controls based on the property type.

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

Ive struggled some with TypeDescriptor.AddAttribute but I cant get it to work. Does anyone had any luck with this scenario?

Edit: 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.

Before rendering my viewmodel I decorate the properties with TypeDescriptor TypeDescriptor.AddAttributes(propertyViewModel.Value, new EmailAttribute()); TypeDescriptor.AddAttributes(propertyViewModel.Value, new RequiredAttribute());

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.

public class TypeDescriptorModelValidationProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {

        var attributesList = new List<Attribute>(TypeDescriptor.GetAttributes(metadata.Model).Cast<Attribute>());


        return base.GetValidators(metadata, context, attributesList);
    }
}

Which I replace the current with at startup

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new TypeDescriptorModelValidationProvider());
Niclas
  • 217
  • 3
  • 9

0 Answers0