MVC model not updated

Model

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

Controller action

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

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.State) @Html.DropDownListFor(model => model.State, (IEnumerable<SelectListItem>)ViewBag.States, new { style = "width:217px;" }) @Html.ValidationMessageFor(model => model.State) </div> <div class="formrow"> @Html.LabelFor(model => model.Zip) @Html.TextBoxFor(model => model.Zip) @Html.ValidationMessageFor(model => model.Zip) </div> 

The problem is that when a city changes, it never reflects on the view. During debugging, model.City contains the correct value, but it does not appear in the view. Even just as @Html.TextBoxFor(model => model.City) does not display the correct value of model.City .

+6
source share
1 answer

HtmlHelpers get the model values ​​from the state of the model, not the model when you update and return the model. To update and return the model, add this line of code to your post method:

 ModelState.Clear(); 

or you can set the city value in ModelState itself:

 ModelState["City"].Value = GetCityByZip(model.Zip); 
+17
source

Source: https://habr.com/ru/post/922255/


All Articles