9

The attribute, DisplayFormatAttribute.ConvertEmptyStringToNull has a default of true. I would like to default it to false for the entire site (or by class or page would be good too). Is there a way I can do this so I don't need to decorate each test form field with:

[DisplayFormat(ConvertEmptyStringToNull=false)]
Brettski
  • 19,351
  • 15
  • 74
  • 97

1 Answers1

16

You can create your own custom model metadata provider like this:

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, System.Type containerType, System.Func<object> modelAccessor, System.Type modelType, string propertyName)
    {
        var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        if (string.IsNullOrEmpty(propertyName)) return modelMetadata;

        if (modelType == typeof(String))
                modelMetadata.ConvertEmptyStringToNull = false;

        return modelMetadata;           
    }
}

Then register it in your app_start:

ModelMetadataProviders.Current = new CustomModelMetadataProvider();
Brian MacKay
  • 31,133
  • 17
  • 86
  • 125
Paul
  • 12,392
  • 4
  • 48
  • 58