Skip to content

Instantly share code, notes, and snippets.

@kenegozi
Created August 22, 2011 21:23
Show Gist options
  • Save kenegozi/1163635 to your computer and use it in GitHub Desktop.
Save kenegozi/1163635 to your computer and use it in GitHub Desktop.
Allowing MVC3 model validator to use interface attributes
// within Application_Start:
ModelMetadataProviders.Current = new IncludeInterfacesModelMetadataProvider();
class IncludeInterfacesModelMetadataProvider : DataAnnotationsModelMetadataProvider {
protected override IEnumerable<Attribute> FilterAttributes(Type containerType, PropertyDescriptor propertyDescriptor, IEnumerable<Attribute> attributes) {
var validationAttributesOnInterfaces =
from i in containerType.GetInterfaces()
from p in i.GetProperties()
where p.Name == propertyDescriptor.Name
from a in p.GetCustomAttributes(true).Cast<Attribute>()
where typeof(ValidationAttribute).IsAssignableFrom(a.GetType())
select a;
attributes = validationAttributesOnInterfaces.Concat(attributes);
return base.FilterAttributes(containerType, propertyDescriptor, attributes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment