我有一個視圖來創建一個用戶,如下所示。查看數據字典在ASP.NET MVC中重寫模型數據
<% using (Html.BeginForm("SaveUser", "Security")) {%>
<p>
<label for="UserName">UserName:</label>
<%= Html.TextBox("UserName") %>
<%= Html.ValidationMessage("UserName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.TextBox("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
<}%>
當點擊「創建」按鈕,在HTML表單發送名爲「SaveUser」的行動只接受如下的「POST」動詞。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveUser(UserViewModel user)
{
//user.Id is zero before save
//Save the user. Code omitted...
//user.Id is now greater than zero
//redirect to edit user view
return View("EditUser", user);
}
用戶保存後,頁面會被重定向到「EditUser」視圖與
<p>
<label for="Id">Id:</label>
<%= Html.Hidden("Id", Model.Id)%>
</p>
這裏的問題是:爲隱藏字段的值保持顯示爲零點雖然。 Model.Id
大於零。看起來其他的東西正在壓倒模型視圖的價值。 ViewDataDictonary
是一個嫌疑人。因此,在返回操作中的視圖之前添加一行,如下所示。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveUser(UserViewModel user)
{
//user.Id is zero before save
//Save the user. Code omitted...
//user.Id is now greater than zero
//clear the view data
ViewData = new ViewDataDictionary();
//redirect to edit user view
return View("EditUser", user);
}
果然,這工作。隱藏字段現在具有正確用戶標識的值。
我們找到了治療症狀的方法,但是問題的根源在哪裏?
我不喜歡在每次返回另一個視圖之前清理視圖數據字典的想法。
++,這是處理這種情況的首選方法。它還解決了用戶刷新頁面和無意中重新發布相同表單帖子的問題。根據系統的不同,如果你的行爲不是冪等的,那可能是一件壞事。 – 2009-10-13 14:47:26
@LukLed,@Joel:謝謝你們的幫助。 我的UserViewModel比我在這裏發佈的更復雜,因此我編寫了自定義模型綁定器。我的一個朋友找到了一種方法來使用默認的聯編程序,而不使用自定義聯編程序,所以我會努力切換到它。 – 2009-10-13 17:02:11
@LukLed:使用RedirectToAction後,問題仍然存在,我不得不使用ViewData = new ViewDataDictionary();換句話說,使用重定向並不能解決問題。有什麼我失蹤? – 2009-10-14 01:17:57