lucamilan
6/10/2012 - 10:07 AM

Allowing MVC3 model validator to use interface attributes

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);
	}
}