views:

464

answers:

1

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

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?

Chris Roberts
Exactly. It makes the 'required' property very confusing and unusable.I since found Jeremy Skinner having the same issues with it. http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/
redsquare