在这种情况下,我试图将一个属性附加到特定属性,但问题出在此代码中,它也附加到了生日日期时间属性。这可能是什么问题
public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
if ( metadata.PropertyName == "FirstName")
attributes = new List<Attribute>() { new RequiredAttribute() };
return base.GetValidators(metadata, context, attributes);
}
}
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
}
protected void Application_Start()
{
//ModelValidatorProviders.Providers.Clear();
//ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());
ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
有人可以解释 GetValidators 是如何工作的吗?