ASP.NET MVC - Data Annotations - Why add a default RequiredAttribute?
- by redsquare
Can anyone explain why it is assumed that a non nullable type property should always have a RequiredAttribue?
I am trying to write a label helper that will auto append * or change the css class so that I can indicate to the user that the field is required. However when querying the metadata the non nullable properties end up with a required attribute.
MVC Source Code:
protected override IEnumerable<ModelValidator> GetValidators(
ModelMetadata metadata, ControllerContext context,
IEnumerable<Attribute> attributes)
{
_adaptersLock.EnterReadLock();
try
{
List<ModelValidator> results = new List<ModelValidator>();
if (metadata.IsRequired &&
!attributes.Any(a => a is RequiredAttribute))
{
//******* Why Do this?
attributes = attributes.Concat(new[] { new RequiredAttribute() });
}
foreach (ValidationAttribute attribute in
attributes.OfType<ValidationAttribute>())
{
DataAnnotationsModelValidationFactory factory;
if (!_adapters.TryGetValue(attribute.GetType(), out factory))
factory = _defaultFactory;
results.Add(factory(metadata, context, attribute));
}
return results;
}
finally
{
_adaptersLock.ExitReadLock();
}
}