Asp.Net Core Model binding, how to get empty field to bind as a blank string?

后端 未结 2 648
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 16:45

If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the correspondi

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 16:52

    Studying the Asp.Net Core code for the SimpleTypeModelBinder at https://github.com/aspnet/Mvc/blob/rel/1.1.3/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/SimpleTypeModelBinder.cs I could see that there is a ModelMetadata.ConvertEmptyStringToNull setting which is set to true by default that is causing the blank string to be converted to null on data binding. But the property is read only so at first I couldn't figure out how to changes it's value.

    @rsheptolut's post on this page https://github.com/aspnet/Mvc/issues/4988 led me to a solution.

    Solution:

    The value has to get set at startup. This can be done via this class:

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

    when it's hooked int into MvcOptions in the ConfigureServices method of the startup.cs file like so

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

    Now site wide, the default for a blank field that is posted back will be for the data binder to set the corresponding model property to a blank string rather than to null. Yea!

提交回复
热议问题