开发者

ASP.NET MVC - Data Annotations - Why add a default RequiredAttribute?

开发者 https://www.devze.com 2022-12-18 05:27 出处:网络
Can anyone explain why it is assumed that a non nullable type property should always have a RequiredAttribue?

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();
    }
}


Personally, I think it's because the designers of the framework have missed the point with nullable data!

It would appear that they have assumed that if a field isn't nullable, it must be required.

Unfortunately, as you're presumably discovering, this isn't always the case.

The most common instance of this I can think of is a text field which is provided by a user that could be blank, but you want to keep it as NULL until the user has provided a value. In this case you get three valid cases: 'Not Set' (NULL), 'Empty' (not NULL) or an actual value.

So - to answer your question, no - I can't explain it. Perhaps it's a mistake?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号