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();
I can't believe there aren't 100 comments thanking you for this. Goodbye null checks or ConvertEmptyStringToNull options everywhere. Thanks!
ReplyDeleteThanks... I also use a trim model binder
ReplyDeletei prefer model binder approach instead applying filter on 'N' properties.
ReplyDelete