This is intended as one of a series of posts on ASP.MVC 3 (Razor) about tips and traps as I learn, feel free to comment with advice or anything to help me or others.

 

One weird thing I noticed on my MVC form was that it didn’t update input values after a post action if I changed the model value which should be using. It would set the value the first time in the get action, but any subsequent requests would keep the initial value. I had a requirement to update a textbox value to uppercase after a search action but nothing I did in the model would affect the value in the input.

 

Turns out it was caused by my using an HtmlHelper for my input:

Image001

 

It seems all the HtmlHelpers (dropdownlist/hidden/textarea included) will try to use the posted value if it is present rather than a value from the model, under the assumption that a post which returns to the same view is dealing with validation and should display the same data.

 

To avoid this you have three options:

·         Don’t use a helper, write the input tag and set the value to your model property directly (annoying).

·         Use ModelState.Clear() in your controller post action, which will remove all post data and force the helper to use the model (nuke it from orbit! Careful, this will clear all form values

      Clear the values you want to update individually, using "ModelState.SetModelValue(key, new ValueProviderResult(null, string.Empty, System.Globalization.CultureInfo.InvariantCulture));" (I added an extension method to do this rather with just the key)