2012-08-31 32 views
5

在很多情況下,我遇到了一個問題,我在服務器上創建了一個模型,作爲返回值的結果。在處理模型時,一些模型值將被更改,然後在頁面上重新顯示。是否有一些簡單的方法來覆蓋導致MVC框架使用POSTed值而不是我的模型值的行爲。MVC3:如何強制Html.TextBoxFor使用模型值而不是POSTed值

實施例:

模型

public class MyModel { 
    public string Value1 { get; set; } 
} 

控制器

public MyController : Controller { 
    public ActionResult MyAction() { 
     var model = new MyModel(); 
     model.Value1 = "OldValue"; 
     return View(model); 
    } 
    [HttpPost] 
    public ActionResult MyAction(MyModel model) { 
     model.Value1 = "NewValue"; 
     return View(model); 
    } 
} 

查看

@using(Html.BeginForm("MyAction", "My", FormMethod.Post) { 
    @Html.TextBoxFor(m => m.Value1) 
    <input type="submit"/> 
} 

當第一次加載該頁面,文本框將包含 「的OldValue」。點擊提交後,文本框仍然包含「OldValue」,因爲這是POST回服務器,但我希望它用來自模型(NewValue)的值創建第二頁(在POST之後)。

有沒有一種簡單的方法來告訴MVC這樣表現?我不確定我在這種情況下應該做什麼來獲得我想要的結果。

注 - 這是所有的僞代碼,所以我可能有一些錯誤,但概念應該在那裏。

回答

8

在您的文章重定向(後 - 重定向 - 獲取模式)。

[HttpPost] 
public ActionResult MyAction(MyModel model) { 
    model.Value1 = "NewValue"; 
    return RedirectToAction("MyAction"); 
} 

編輯

清除模型的狀態回傳的編輯模式

[HttpPost] 
    public ActionResult MyAction(MyModel model) 
    { 
     var newModel = new MyModel(); 
     newModel = model; 
     ModelState.Clear(); 
     newModel.Value1 = "NewValue"; 
     return View(newModel); 
    } 
+0

感謝您的建議,但我的例子是簡化了,我真的不想只是重定向到GET。我想我可以做這個工作,但我希望有一個解決方案可以讓模型重寫POST的值。 –

+0

@LeslieHanks - 對不起,誤解,請參閱我的編輯。 –

+0

更多詳細信息,請訪問:http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx –

0

沒有辦法使用內置的助手去做。您必須手動

做使用helper得到名字:

<input type="text" name="@Html.NameFor(m => m.MyField)" value="@Model.MyField"/> 
相關問題