1

In my application I am using a class that is supplied by external library, and used across multiple applications. I would like to add Data Annotations to the properties of this class, but it must be contained within my application.

I've produced the following code that will retrieve all attributes for a property, but cannot find a way to add a Data Annotation attribute. Lets say I have a class called vehicle that has a property of VIN:

AttributeCollection oldAttributeCollection = TypeDescriptor.GetProperties(instance).Find("VIN", true).Attributes;
tereško
  • 58,060
  • 25
  • 98
  • 150
  • dear one thing you can do get the data from there dll and create your own poco class and map the dll class with your own class and then put data annotation on your class :D – Developerzzz Feb 04 '14 at 06:38

3 Answers3

1

The short answer is you can't add attributes to a class dynamically. For more info see this related question

Community
  • 1
  • 1
Nathan
  • 1,016
  • 7
  • 16
1

I found the solution. The method below will execute for each property in the current model. I am able to apply some logic and determine if I want to add my custom "ConditionallyRequired" Data Annotation to the property.

  public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {
            var validators = PermissionManager.Settings.Validation.ToList();
            var validateField =
                validators.SingleOrDefault(v => v.FieldName == metadata.PropertyName && v.IsValidated == "True");

            var attr = new List<Attribute>();
            attr.AddRange(attributes);
            if (validateField != null)
            {

                attr.Add(new ConditionallyRequired(validateField.FieldName));
            }
            return base.GetValidators(metadata, context, attr);
        }
    }

Then initialize the CustomMetadataValidationProvider class in the global.asax like so:

protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Add(new ConditionallyRequired.CustomMetadataValidationProvider());
        AreaRegistration.RegisterAllAreas();

    }
-1

right click on your class library and choose Manage NuGet Packages... and in Browse tab --> wirte: System.ComponentModel.DataAnnotations and install