I have mentioned that empty strings never have null values during data binding. Instead they are empty strings. If we don’t do anything with it, it will propagate to the database. I don’t really want to have empty strings in there. Nulls should be in the database instead. The easiest solution is to re-implement the default data-binder. And here it is:
I don’t know if this is a good solution and for me it really seems the empty values should be bound as NULLs for strings. The reasoning is simple: if user does not provide value it is null. With this solution user cannot provide an empty string, but I can live with it for now.
One options would be NOT to post empty values. But it would not set NULLs to the actual objects if there some other value assigned. Additionally it is not out-of-the box functionality in ASP.NET MVC.
Thou, would be interesting to know a perfect solution for this.
public class NullStringModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(string)) { ValueProviderResult result; bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out result); if (result != null) { try { var str = (string)result.ConvertTo(typeof(string)); if (string.IsNullOrEmpty(str)) return null; // These two lines are the only ones I need return str; } catch (Exception ex) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex); // Don't forget to set value to Workaround ASP.NET MVC bug bindingContext.ModelState.SetModelValue(bindingContext.ModelName, new ValueProviderResult(null, null, CultureInfo.CurrentCulture)); } } } return base.BindModel(controllerContext, bindingContext); } }
I don’t know if this is a good solution and for me it really seems the empty values should be bound as NULLs for strings. The reasoning is simple: if user does not provide value it is null. With this solution user cannot provide an empty string, but I can live with it for now.
One options would be NOT to post empty values. But it would not set NULLs to the actual objects if there some other value assigned. Additionally it is not out-of-the box functionality in ASP.NET MVC.
Thou, would be interesting to know a perfect solution for this.