Last active
November 6, 2021 09:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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