This is a MVC feature which binds empty strings to nulls.
This logic is controlled with the ModelMetadata.ConvertEmptyStringToNull property which is used by the DefaultModelBinder.
So what youYou can do isset the ConvertEmptyStringToNull with the DisplayFormat attribute
public class OrderDetailsModel
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Comment { get; set; }
//...
}
However if you don't want to annotate all the properties you can create a custom model binder where you set it to false:
public class EmptyStringModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
Binders = new ModelBinderDictionary() { DefaultBinder = this };
return base.BindModel(controllerContext, bindingContext);
}
}
And you can use the ModelBinderAttribute in your action:
public ActionResult SaveOrderDetails([ModelBinder(typeof(EmptyStringModelBinder))]
OrderDetailsModel orderDetailsModel)
{
}
Or you can set it as the Default ModelBinder globally in your Global.asax:
ModelBinders.Binders.DefaultBinder = new EmptyStringModelBaseBinderEmptyStringModelBinder();
You can read more about this feature here.