2011-08-22 99 views
4

我有一個窗體在我的MVC應用程序有一個文本框。將表單發佈到頁面後,我將修改模型值並重新顯示視圖。該文本框仍顯示已發佈的值。ASP.net MVC - 文本框值保留已發佈的值

下面是代碼:

@using(Html.BeginForm()) { 
    @Html.TextBoxFor(m => m.Foo) 
    <input type="submit" value="Save" /> 
} 

public class TestController : Controller { 
    public ActionResult Index() { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(MyModel model) { 
     model.Foo += "bar"; 

     return View(model); 
    } 
} 

無論是在形式(可以說,我在Foo類型不同)我加上「欄」,並嘗試再次顯示形式。但是當表單重新顯示時,我看到的只有foo。我記得讀過一些關於爲什麼會發生這種情況的事情,但現在看來似乎無法找到它。我知道這是一個不好的例子,但我只是想記住它爲什麼這樣做,以及解決方法是什麼(除了重定向)。有沒有辦法讓它顯示更新的模型值,而不是發佈的表單值?

+0

錯字? 'Html.BeingForm()' –

+0

顯然.. :-) – Dismissile

回答

2

您可以清除模型狀態,助手應顯示新值。

[HttpPost] 
public ActionResult Index(MyModel model) { 
    model.Foo += "bar"; 
    ModelState.Clear(); 
    return View(model); 
} 
+0

這樣做伎倆謝謝。 – Dismissile

+0

雖然它起作用,但似乎它可能不是最好的方法(如果有的話),因爲它可能會導致一些意想不到的結果。 [http://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear](http://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear) – brheal