I have been trying to add validation attributes dynamically at runtime and all works ok.
I next tried to add a DisplayAttribute at runtime hooking into the same
public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
List<Attribute> newAttributes = new List<Attribute>(attributes);
if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "LastName")
{
//add a new one -WORKS!
StringLengthAttribute attr = new StringLengthAttribute(25);
attr.MinimumLength = 2;
newAttributes.Add(attr);
}
if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "City")
{
//add a new one - does not work
DisplayAttribute attr = new DisplayAttribute();
attr.Name = "The Big City";
newAttributes.Add(attr);
}
return base.GetValidators(metadata, context, newAttributes);
}
}
snuggles
Member
20 Points
49 Posts
Dynamic Attributes - DisplayAttribute
Nov 24, 2010 05:50 AM|LINK
I have been trying to add validation attributes dynamically at runtime and all works ok.
I next tried to add a DisplayAttribute at runtime hooking into the same
public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider { protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) { List<Attribute> newAttributes = new List<Attribute>(attributes); if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "LastName") { //add a new one -WORKS! StringLengthAttribute attr = new StringLengthAttribute(25); attr.MinimumLength = 2; newAttributes.Add(attr); } if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "City") { //add a new one - does not work DisplayAttribute attr = new DisplayAttribute(); attr.Name = "The Big City"; newAttributes.Add(attr); } return base.GetValidators(metadata, context, newAttributes); } }attribute