Why does ASP.NET MVC care about my read only properties during databinding?

This looks for all the world like a bug to me. I fully can't understand why the ModelBinder needs to check my read only properties (there may be some technicalities, but I definitely don't understand, and am not willing to spend the time trying to).

I added the following Model Meta Data Provider in to my solution to get round the problem

protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
{
    var metadata = base.CreateMetadataPrototype(attributes, containerType, modelType, propertyName);

    if (metadata.IsReadOnly)
    {
        metadata.IsRequired = false;
    }

    return metadata;
}

protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
{
    var metadata = base.CreateMetadataFromPrototype(prototype, modelAccessor);

    if (prototype.IsReadOnly)
    {
        metadata.IsRequired = false;
    }

    return metadata;
}

You will also need to add the following to Global.asax.cs

protected void Application_Start()
{
    ModelMetadataProviders.Current = new RESModelMetadataProvider();
    ModelBinders.Binders.Add(typeof(SmartDate), new SmartDateModelBinder());

    ...
}

I believe I'm experiencing a similar issue. I've posted the details:

http://forums.asp.net/t/1523362.aspx


edit: Response from MVC team (from above URL):

We investigated this and have concluded that the validation system is behaving as expected. Since model validation involves attempting to run validation over all properties, and since non-nullable value type properties have an implicit [Required] attribute, we're validating this property and calling its getter in the process. We understand that this is a breaking change from V1 of the product, but it's necessary to make the new model validation system operate correctly.

You have a few options to work around this. Any one of these should work:

  • Change the Date property to a method instead of a property; this way it will be ignored by the MVC framework.
  • Change the property type to DateTime? instead of DateTime. This removes the implicit [Required] from this property.
  • Clear the static DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes flag. This removes the implicit [Required] from all non-nullable value type properties application-wide. We're considering adding in V3 of the product an attribute which will signal to us "don't bind it, don't validate it, just pretend that this property doesn't exist."

Thanks again for the report!


Still having the same issue with MVC3.

I think the best way is to just to this in global.asax (from SevenCentral's answer):

 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

This will disable for all of them