As my last post indicated, I wasn't sure where SetAttemptedValue on ModelStateDictionary had gone, or what has replaced it. With a little bit of experimenting I noticed that if I used the SetModelValue method, which I suspect is new with 1.0 RC, it would display the input that failed to validate. Which pretty much behaves the same way it was before with SetAttemptedValue(string key, string value). However, there is one difference, if I don't use the SetModelValue I'll get a NullReferenceException from MVC. Before it just displayed the default value. Looking in the source code for MVC 1.0 Release Candidate and Beta 1, I noticed it's been through a major refactoring.
Before in Beta 1, it used the following code to get the attempted value:
string attemptedValue = htmlHelper.GetModelAttemptedValue(name);
And uses the attemptedValue as value for the textbox in my case. Displaying the input the user tried to enter.
However, in 1.0 RC it's gone. Instead it tries to get the value from the model state with the following method:
internal object GetModelStateValue(string key, Type destinationType) {
ModelState modelState;
if (ViewData.ModelState.TryGetValue(key, out modelState)) {
return modelState.Value.ConvertTo(destinationType, null /* culture */);
}
return null;
}
Debugging the application shows the error, the ViewData.ModelState contains the key and returns true. The modelState variable however only contains the list of ModelErrors in Errors (which contains 1 error). The Value is unfortunately null. Which of course will be a NullReferenceException when trying to use
modelState.Value.ConvertTo(destinationType, null)
Probably I've just missed this change in the documentation and it's always been mandatory to set the value in the modelState, but it really shouldn't throw a NullReferenceException.
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) in ...
System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType ...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Ob...
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5