ASP.NET MVC - Data Annotations - Why add a default RequiredAttribute?
Posted
by redsquare
on Stack Overflow
See other posts from Stack Overflow
or by redsquare
Published on 2010-01-25T15:57:20Z
Indexed on
2010/04/03
6:33 UTC
Read the original article
Hit count: 467
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();
}
}
© Stack Overflow or respective owner