Art Of Programming

musings by Dmytrii Nagirniak

ASP.NET MVC Empty Values and String Binding

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:
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.


Works a treat I mean!
Wors a treat - cheers for that!
Dmytrii Nagirniak
I don't want to store any value if user did not provide such. Thus it should be NULL.

Additionally ASP.NET MVC 2 will bind the empty string values as NULLs by default. And this is what i expected in ASP.NET MVC 1 as well. Unfortunately it is not the case and I have to fix it manually.
Sometimes you should store an empty value instead of null.

Some controls in my application have EmptyIsNull property wich I use to tell databinding how to store empty values.