Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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());
share|improve this question
    
Can you show us what you've tried so far with TypeDescriptor.AddAttribute()? –  Sven Grosen Jun 13 at 13:53
    
Possible replica of this question: link –  Claudio P Jun 13 at 14:05
    
Its no exactly what I want to do accomplish. See the solution in my updated question –  Niclas Jun 16 at 7:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.