2013-06-20 58 views
1

我有一個簡單的發佈操作,試圖將新模型返回到post方法的視圖。出於某種原因,當我返回新模型時,我總是看到我發佈的模型,爲什麼會發生這種情況?我需要在後期操作中更改模型的值並將其返回給用戶,但出於某種原因,我無法做到這一點?ASP.NET MVC後發佈返回錯誤的模型值

public ActionResult Build() 
{ 
    return View(new Person()); 
} 

[HttpPost] 
public ActionResult Build(Person model) 
{ 
    return View(new Person() { FirstName = "THX", LastName = "1138" }); 
} 

這是視圖代碼;

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>Person</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.FirstName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.FirstName) 
      @Html.ValidationMessageFor(model => model.FirstName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.LastName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.LastName) 
      @Html.ValidationMessageFor(model => model.LastName) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

如果我打開窗體,鍵入「約翰」的名字和「史密斯」的姓氏和張貼我得到「約翰」,「史密斯」從帖子的動作後面,而不是「THX形式1138「有沒有辦法來覆蓋這種行爲?我也想知道它爲什麼這樣做?

+0

在哪裏,告訴提交按鈕來調用'Build'動作的代碼? – jbabey

+0

你能顯示生成的HTML嗎? –

+0

您是否在「public ActionResult Build(Person model)」中放置了斷點以確保它是綁定的操作方法? – Rob

回答

4

您可以通過添加this.ViewData = null;到您的文章採取行動指示ASP.NET MVC忘記貼值做到這一點:

[HttpPost] 
public ActionResult Build(Person model) 
{ 
    this.ViewData = null; 

    return View(new Person() { FirstName = "THX", LastName = "1138" }); 
}