2012-08-07 21 views
6

模型MVC模式不更新

class Address 
{ 
    public string Street { get; set; } 
    public string City { get; set; } 
    public string State { 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.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> 

的問題是每當這個城市正在被修改,使它不會被反映在風景。在調試過程中,model.City包含正確的值,但它不會顯示在視圖中。即使像@Html.TextBoxFor(model => model.City)這樣簡單的東西也不會顯示正確的model.City值。

+0

你能後的視圖? – 2012-08-07 02:06:18

+1

您發佈的模型和您作爲參數傳遞的模型不一樣。你引用了錯誤的模型嗎? – Tommy 2012-08-07 02:07:05

+0

@MarkOreta:更新了問題,添加了視圖 – xar 2012-08-07 02:14:23

回答

17

當您更新並返回模型時,HtmlHelpers將從模型狀態獲取模型值,而不是模型。爲了更新和返回模型,加入這行代碼在帖子中的方法:

ModelState.Clear(); 

,或者你可以設置城市價值中的ModelState本身:

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

這很有道理。這是所有版本的MVC的情況嗎? – xar 2012-08-07 02:53:33

+0

據我所知,是的。模型狀態告訴關於有效/無效屬性的視圖等。 – Tommy 2012-08-07 03:46:29

+2

這必須在Aprils愚人節實施......謝謝。 (剛剛在我的服務器端和客戶端代碼上看了2個小時,我應該早點開始使用Google搜索...) – 2017-09-18 04:27:15