2013-09-27 152 views
1

我的模型;模型返回查看對字段沒有影響

namespace GeneralUtility.Models 
{ 
    public class MyModel 
    { 
    public int BirthDateYear { get; set; } 
    public String Details { get; set; } 
    } 
} 

我的控制器

namespace GeneralUtility.Controllers 
{ 
    public class WorkspaceController : Controller 
    { 
    public ActionResult MyHelper(MyModel model) 
    { 
     if(model.someCondition) 
     model.Details= "TEST"; 
     else 
     model.Details= "Some other TEST"; 

    return View(model); 
    } 
    } 
} 

我查看

<div data-role="fieldcontain"> 
    @using (Html.BeginForm("MyHelper", "WorkSpace", FormMethod.Post, new { id = "frmMyForm" })) 
    { 
    ... 
    <div data-role="fieldcontain"> 
     @Html.EditorFor(x => x.Details) 
    </div> 
    ... 
    } 
</div> 

後提交我的形式,我可以看到MyHelper操作方法的模型和任何改變我做。但是,當我進行更改並從控制器返回模型時(我可以在調試時看到模型中的更改)。我在@Html.EditorFor(x => x.Details)字段中獲得與以前相同的值。我能做些什麼來獲取模型的更改的Details值以顯示?

+1

您是否曾嘗試在if語句前使用'ModelState.Clear()' – AthibaN

+0

我假設您使用的是GeneralUtility.Models.MyModel的強類型視圖? – Botonomous

+0

我剛剛嘗試過,它的工作原理。謝謝。如果您發佈答案,我會接受它。如果你能告訴我爲什麼它有效,我將不勝感激。我認爲它清除了模型內容,但似乎沒有這樣做。 – mechanicum

回答

2

這是因爲默認情況下,ASP.NET MVC會返回傳入方法的模型(使用存儲在ModelState中的內容,如果存在的話)。如果它不存在,它會使用您傳遞給View的內容。

爲了防止出現這種情況,您需要在返回視圖前致電ModelState.Clear()

查詢this blog post的更詳細的解釋。