ASP.NET MVC 1.0 issue within HtmlHelper.GetModelStateValue method
It all started innocently…
I had the simplest form ever. Just a few text inputs, and one checkbox. State of one of the text inputs was determined by status of one the checkbox. If checkbox was not checked (or “on”) input was set to be disabled. As simple as that.
As you probably know, controls that are disabled are not treated as valid for submission. So there was no form element for it at server side (Request.Form had no entry with such a key). During validation phase i was checking for this input – since it was not send and then null, validation failed, and i was adding model error. Like that:
if (notify && (string.IsNullOrEmpty(notifyEmail))) _modelState.AddError("notifyEmail", "Pleave provide email....");
Notify value represent checkbox and notifyemail – text input. So, the problem arrived when i was trying to redisplay form – due to errors in model state. I had error under:
< %= Html.TextBox("notifyEmail") %>
System.NullReferenceException: Object reference not set to an instance of an object.
System.Web.HttpUnhandledException: Exception of type ‘System.Web.HttpUnhandledException’ was thrown. —> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType)
at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, Object htmlAttributes)
It looks like there is a problem because there is a model state error and no original value being set. It is used for some of controls under HtmlHelpres. It is rather serious issue. Just imagine it may happen for radio buttons (without any of them being “on”) as well. Simplest possible solution (or rather workaround) is to set different modelstate key and then use it as validation key message under textbox, like:
if (notify && (string.IsNullOrEmpty(notifyEmail))) _modelState.AddError("notifyEmailErr", "Pleave provide email....");
< %= Html.TextBox("notifyEmail") %> < %= Html.ValidationMessage("notifyEmailErr") %>
Hope it will help someone….
It looks like ASP.NET MVC 2.0 preview 1 has this one fixed…