Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false across site

Tags:

asp.net-mvc

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)]
like image 785
Brettski Avatar asked Sep 18 '11 04:09

Brettski


1 Answers

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();
like image 117
Paul Avatar answered Jan 03 '23 14:01

Paul