Skip to content

Instantly share code, notes, and snippets.

@dburriss
Last active November 6, 2021 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dburriss/81935798ac077be7c2c47d8aad333b0e to your computer and use it in GitHub Desktop.
Save dburriss/81935798ac077be7c2c47d8aad333b0e to your computer and use it in GitHub Desktop.
Code required to create a model binder that sets or empty or no strings to empty string during binding
//In Startup.cs file
services.AddMvc(config =>
config.ModelBinderProviders.Insert(0, new NoNullStringModelBinderProvider())
);
//model binder provider
public class NoNullStringModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (!context.Metadata.IsComplexType)
{
var propName = context.Metadata.PropertyName;
var propInfo = context.Metadata.ContainerType.GetProperty(propName);
if (propInfo.PropertyType == typeof(string))
return new NoNullStringModelBinder(context.Metadata.ModelType);
}
return null;
}
}
//model binder
public class NoNullStringModelBinder : IModelBinder
{
private SimpleTypeModelBinder _baseBinder;
public NoNullStringModelBinder(Type type)
{
_baseBinder = new SimpleTypeModelBinder(type);
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult != ValueProviderResult.None)
{
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
object result = null;
var valueAsString = valueProviderResult.FirstValue;
var success = false;
if (string.IsNullOrEmpty(valueAsString))
{
success = true;
result = string.Empty;
}
if (success)
{
bindingContext.Result = ModelBindingResult.Success(result);
return Task.CompletedTask;
}
}
return _baseBinder.BindModelAsync(bindingContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment