NullReferenceException when model binding strings after upgrading from ASP.NET MVC 1 to ASP.NET MVC 2
- Mar 18, 2013
When migrating a site from ASP.NET MVC 1 to ASP.NET MVC 2, you can generally follow the instructions in http://www.asp.net/whitepapers/what-is-new-in-aspnet-mvc#_TOC2, taking note of any breaking changes. This will take you most of the way there, however there are a few undocumented issues which you may uncover if you’re migrating a site with a substantial amount of code.
By default, the ASP.NET MVC 1 model binder would initialize strings to string.Empty whereas ASP.NET MVC 2 will initialize strings as NULL. This is an undocumented breaking change and will be a problem if you have a substantial amount of code relying on the original behavior – code that was previously working in production will start throwing NullReferenceException.
To preserve the original MVC 1 model binder behaviour, consider creating default model binder such as the following:
public class MVC1ModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; return base.BindModel(controllerContext, bindingContext); } }
and in global.asax.cs, make sure you have the following:
protected void Application_Start() { ModelBinders.Binders.DefaultBinder = new MVC1ModelBinder(); }