Assuming I have a form, and the value of "" is selected when the form is sent from the view to the controller to the action method, will asp.net core convert the empty string to a NULL value?
If I do not make the Boolean property nullable for the [required] attribute, it gives me this error: The value '' is invalid.
Does this mean that: "" is evaluated as NULL, the Boolean property does not allow NULL, asp.net core returns a error saying that you can not pass a empty string to the Model property because it is not nullable because asp.net core converts the empty string to a NULL?
MVC model binding does support binding an empty string as either a null or empty string, depending on metadata.
You can control that behaviour per field with attributes;
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Property { get; set; }
Or override that behaviour globally by implementing a custom IDisplayMetadataProvider.
public class DisplayProvider : IDisplayMetadataProvider
{
public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
{
if (context.Key.ModelType == typeof(string))
context.DisplayMetadata.ConvertEmptyStringToNull = false;
}
}
// in .AddMvc(o => ...) / AddControllers(o => ...) / or an IConfigure<MvcOptions> service
[MvcOptions].ModelMetadataDetailsProviders.Add(new DisplayProvider());
Or convert values in any way you like by providing your own IModelBinder / IModelBinderProvider.
public class StringBindProvider : IModelBinderProvider
{
private StringBinder stringBinder = new StringBinder();
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(string))
return stringBinder;
return null;
}
}
public class StringBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != ValueProviderResult.None)
{
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
var str = value.FirstValue?.Trim();
if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && string.IsNullOrWhiteSpace(str))
str = null;
bindingContext.Result = ModelBindingResult.Success(str);
}
return Task.CompletedTask;
}
}
// see above
[MvcOptions].ModelBinderProviders.Insert(0, new StringBindProvider());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With