MVC Model not updating
HtmlHelpers get the model values from the model state and not the model when you update and return the model. In order to update and return the model, add this line of code in your post method:
ModelState.Clear();
or you could set the value of city in the ModelState itself:
ModelState["City"].Value = GetCityByZip(model.Zip);
As Tommy noted, this is, somewhat counterintuitively, the correct behavior since form data submitted on post gets first priority when binding the data to the returned view. This makes some sense as the user is likely to have made a validation error when re-returning the same view and gets to resume their form entry as is without the problems of losing form input when restoring a page
One other option is to manually insert the value for the input
So instead of this:
@Html.TextBoxFor(model => model.City)
Do this instead:
<input type="text" name="City" value="@Model.City" />
* which will grab the value directly off the model
Or even better:
<input type="text" value="@Model.City"
name="@Html.NameFor(model => model.City)"
id="@Html.IdFor(model => model.City)" />
*Note: this won't bring in
data-val
attributes. If you're using them on this property for client side validation, you'll need to build list of data validation attributes for a given element
Additional Resources
- HiddenFor not getting correct value from view model
- HTML.HiddenFor is not updating on a postback
- ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes