I\'m passing an object from client to server. Properties of the object which are represented as string.empty are being converted to null during this process. I was wondering
The accepted answer did not work for me using MVC4. However, the following workaround does and I thought it would help others.
public class CustomModelBinder : DefaultModelBinder
{
public bool ConvertEmptyStringToNull { get; set; }
public CustomModelBinder ()
{
}
public CustomModelBinder (bool convertEmptyStringToNull)
{
this.ConvertEmptyStringToNull = convertEmptyStringToNull;
}
protected override bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// this little bit is required to override the ConvertEmptyStringToNull functionality that we do not want!
foreach (string propertyKey in bindingContext.PropertyMetadata.Keys)
{
if(bindingContext.PropertyMetadata[propertyKey] != null)
bindingContext.PropertyMetadata[propertyKey].ConvertEmptyStringToNull = this.ConvertEmptyStringToNull;
}
return base.OnModelUpdating(controllerContext, bindingContext);
}
}
This will fix the issue under MVC4+. It would seem that bindingContext.ModelMetadata.ConvertEmptyStringToNull is completely ignored, and this is because the setting exists in the PropertyMetadata object for each property being bound. PropertyMetadata is recreated in BindProperty() so if you set it before that method call it will get overwritten unless it exists as an attribute on the property of your object being bound (such as [DisplayFormat(ConvertEmptyStringToNull=false)]). No one wants to do this on every property as that's silly.