谁能解释为什么假定不可为空的类型属性应始终具有RequiredAttribue?
我正在尝试编写一个标签助手,它将自动附加 * 或更改 css 类,以便我可以向用户指示该字段是必需的。但是,在查询元数据时,不可为空的属性最终会带有必需的属性。
MVC 源代码:
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();
}
}