Reputation: 12302
I am trying to attach an attribute to the particular property in the this case the FirstName but the problem is in this code it is attaching to the birthday datetime property as well . what might be the problem with this
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);
}
can someone can explain how GetValidators is working?
Upvotes: 1
Views: 242
Reputation: 139818
Your problem has nothing to do with your GetValidators
method.
Value types like (int, decimal, DateTime, etc.
) are required by default. Because otherwise the model binder cannot set their values if they are not sent with the request.
So you need to change your Birtday
property to nullable if you don't want to be required:
public class User
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Birthday { get; set; }
}
Upvotes: 3