Wednesday 11 September 2013

ConvertEmptyStringToNull in MVC

When using MVC and model binding from a form post there comes a time when your database doesn't allow nulls but you find that any empty string from a form post comes back as null. This might be a PITA if you are directly saving the posted form back to the database and don't want to manually convert string null's to empty strings.

The default behaviour of the DefaultModelBinder, is that ConvertEmptyStringToNull is by default, set to true.

To get around this you can add an attribute to your property that guarantees that the binder will not convert the property to an empty string rather than null.

[DisplayFormat(ConvertEmptyStringToNull = false)]
public virtual string Language { get; set; }

Another way is to do it at a global level is to create your own model binder

public class EmptyStringModelBaseBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;

        return base.BindModel(controllerContext, bindingContext);
    }
}
and add your binder in global.asax
ModelBinders.Binders.DefaultBinder = new EmptyStringModelBaseBinder();