Created
August 22, 2011 21:23
-
-
Save kenegozi/1163635 to your computer and use it in GitHub Desktop.
Allowing MVC3 model validator to use interface attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// within Application_Start: | |
ModelMetadataProviders.Current = new IncludeInterfacesModelMetadataProvider(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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