Search code examples
asp.net-coremodel-binding

Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false in .NET Core


I want to make [DisplayFormat(ConvertEmptyStringToNull = false)] the default behaviour for my fields in an ASP.NET Core web application.

Related questions are for .NET Framework, and I am unsure on how to proceed with .NET Core

Related:

I tried the following based on this post, but it doesn't work and also breaks the attribute when I tried to include it anyways

public class EmptyStringAllowedModelMetadataProvider : DefaultModelMetadataProvider
{
    public EmptyStringAllowedModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider) : base(detailsProvider)
    {
    }

    public EmptyStringAllowedModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider, IOptions<MvcOptions> optionsAccessor) : base(detailsProvider, optionsAccessor)
    {
    }

    public override ModelMetadata GetMetadataForType(Type modelType)
    {
        if (modelType != typeof(string)) return base.GetMetadataForType(modelType);
        var identity = ModelMetadataIdentity.ForType(modelType);
        var details = CreateTypeDetails(identity);
        var context = new DisplayMetadataProviderContext(identity, details.ModelAttributes);
        DetailsProvider.CreateDisplayMetadata(context);
        details.DisplayMetadata = context.DisplayMetadata;
        details.DisplayMetadata.ConvertEmptyStringToNull = false;
        return CreateModelMetadata(details);
    }
}

Solution

  • You can refer to the following way, it works fine:

    CustomMetadataProvider:

    public class CustomMetadataProvider : IMetadataDetailsProvider, IDisplayMetadataProvider
        {
            public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
            {
                if (context.Key.MetadataKind == ModelMetadataKind.Property)
                {
                    context.DisplayMetadata.ConvertEmptyStringToNull = false;
                }
            }
    }
    

    registration service:

    services.AddMvc()
                 .AddMvcOptions(options => options.ModelMetadataDetailsProviders.Add(new CustomMetadataProvider()));
    

    Test Result: enter image description here