Alex Rivera | Logout

Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false across site

Asked 2011-09-18T04:56:23.830
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)]
Edit
Report

1 Answer

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();
answered 2011-09-18T05:36:37.480

Your Answer