Asp.net

MVC 模型未更新

  • August 7, 2012

型號

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

控制器

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

觀點

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

問題是每當城市被修改時,它永遠不會反映在視圖上。在調試期間,model.City包含正確的值,但未顯示在視圖中。即使是簡單的事情@Html.TextBoxFor(model => model.City)也不會顯示正確的model.City值。

當您更新和返回模型時,HtmlHelpers 從模型狀態而不是模型中獲取模型值。為了更新和返回模型,在你的 post 方法中添加這行程式碼:

ModelState.Clear();

或者您可以在 ModelState 本身中設置 city 的值:

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

引用自:https://stackoverflow.com/questions/11838335