If value changes in Model after post, Form still displays old value
Here is the code from the MVC Source for the textbox:
string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string)); tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter**), isExplicitValue); break;
And the Code for GetModelStateValue()
internal object GetModelStateValue(string key, Type destinationType) { ModelState modelState; if (ViewData.ModelState.TryGetValue(key, out modelState)) { if (modelState.Value != null) { return modelState.Value.ConvertTo(destinationType, null /* culture */); } } return null; }
So what happens is the Html "Helper" looks for the text box value, by matching the name, in your ViewData.ModalState, if its in the ModelState dictionary, it completely ignores the value you provided.
So all that if (value > 0) { ValueA = 0; } doesn't matter because its going to use the posted values in ModelState if the names match.
The way I've fixed this is to blow away the ModalState before the view renders for certain values that I want to mess with in my view models. This is some code I've used:
public static void SanitizeWildcards( Controller controller, params string[] filterStrings ) { foreach( var filterString in filterStrings ) { var modelState = controller.ModelState; ModelState modelStateValue; if( modelState.TryGetValue(filterString,out controller.ModelState.SetModelValue(filterString, new ValueProviderResult("","", null)); } }
Clearing the entire ModelState might also do the trick:
ViewData.ModelState.Clear();
thanks jfar.. this is the vb code:
Sub CleanForm(ByVal ParamArray Fields() As String) Dim modelStateValue As ModelState = Nothing For Each Field In Fields If ModelState.TryGetValue(Field, modelStateValue) Then ModelState.SetModelValue(Field, New ValueProviderResult(Nothing, Nothing, Nothing)) End If NextEnd Sub