MVC Model not updating

xar picture xar · Aug 7, 2012 · Viewed 12.8k times · Source

The Model:

class Address
{
    public string City { get; set; }
    public string Zip { get; set; }
}

The Controller:

[HttpPost]
public ActionResult GetAddress(Address model)
{
    if (!String.IsNullOrEmpty(model.Zip))
    {
        model.City = GetCityByZip(model.Zip);
    }
    return View(model);
}

The View:

<div class="formrow">
    @Html.LabelFor(model => model.City)
    @Html.TextBoxFor(model => model.City) 
    @Html.ValidationMessageFor(model => model.City)
</div>
<div class="formrow">
    @Html.LabelFor(model => model.Zip)
    @Html.TextBoxFor(model => model.Zip) 
    @Html.ValidationMessageFor(model => model.Zip)
</div>

The problem is whenever the city is being modified, it never gets reflected on the view. During debugging, the model.City contains the correct value but it doesn't show up on view. Even something as simple as @Html.TextBoxFor(model => model.City) doesn't display the correct model.City value.

Answer

Tommy picture Tommy · Aug 7, 2012

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);