Mr. Grock had a similar problem on this site. He already found a solution to ModelState.Clear () , but wanted an explanation of why it worked. The highest rating on the linked site suggested that the html helper behavior is a bug for which ModelState.Clear () is a workaround. However, the bradwill on this site says that the behavior is by design and gives the following explanation:
The reason we use the published value for editors rather than the model value is because the model cannot contain the value entered by the user. Imagine that in your "int" editor the user typed "dog". You want to display an error message stating that the "dog is invalid" and leave the "dog" in the editor field. However, your model is int: it cannot store a "dog." Therefore, we maintain the old value.
If you do not need the old values ββin the editor, clear the state of the model. Where the old value is stored and pulled from HTML helpers.
Despite the fact that it is by design, this is a very unexpected behavior for the developer, and, unfortunately, interaction with ModelState is required for the general programming need.
In addition, clearing the entire ModelState can cause unforeseen problems in other areas (I think regarding validation on unrelated fields of the model). Many thanks to Peter Gluck (in the comments on Mr. Grox's page) for offering a more limited ModelState.Remove ("key") , and for Toby J for developing a more convenient method that works when you don't know which key should be if the model property is nested. I also like the Tobys method, because it does not depend on the string as input.
This method with minor changes follows:
/// <summary> /// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing /// Model values on the server after a postback, to prevent ModelState entries from taking precedence. /// </summary> /// <param name="model">The viewmodel that was passed in from a view, and which will be returned to a view</param> /// <param name="propertyFetcher">A lambda expression that selects a property from the viewmodel in which to clear the ModelState information</param> /// <remarks> /// Code from Tobi J at /questions/469276/aspnet-mvc-modelstateclear /// Also see comments by Peter Gluck, Metro Smurf and Proviste /// Finally, see Bradwils http://forums.asp.net/p/1527149/3687407.aspx. /// </remarks> public static void RemoveStateFor<TModel, TProperty>( this ModelStateDictionary modelState, TModel model, Expression<Func<TModel, TProperty>> propertyFetcher ) { var key = ExpressionHelper.GetExpressionText(propertyFetcher); modelState.Remove(key); }
pwilcox
source share