0
我有以下GET操作方法: -的ModelState錯誤將保持後顯示刷新頁面
public ActionResult Edit(int id)
{
return View(groupRepository.Find(id));
}
我有以下POST操作方法: -
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Group group)
{
try
{
if (ModelState.IsValid)
{
AuditInfo auditinfo = repository.IntiateAudit(2, 2, User.Identity.Name, 2);
groupRepository.InsertOrUpdate(group);
groupRepository.Save();
repository.InsertOrUpdateAudit(auditinfo);
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var clientValues = (Group)entry.Entity;
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink."); }
但問題是,在如果引發(DbUpdateConcurrencyException),那麼在用戶刷新頁面後,ModelState錯誤將繼續顯示。
第二個問題是刷新後舊值將繼續顯示,而不是從數據庫中查看更新的值。
但是,如果我點擊瀏覽器URL並單擊「Enter」,那麼錯誤將被刪除,並且值將從數據庫中檢索,不像刷新頁面。
最後查找方法是: -
public Group Find(int id)
{ return context.Groups.Find(id) ;}
::編輯::
我已經更新我的博客上編輯的操作方法是: -
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (Group)entry.GetDatabaseValues().ToObject();
entry.Reload();
var clientValues = (Group)entry.Entity;
ModelState.AddModelError(string.Empty, "The record you attempted to edit "
+ "was modified by another user after you got the original value. The "
+ "edit operation was canceled and the current values in the database "
+ "have been displayed. If you still want to edit this record, click "
+ "the Save button again. Otherwise click the Back to List hyperlink.");
// department.Timestamp = databaseValues.Timestamp;
group.timestamp = databaseValues.timestamp;
但仍在顯示ModelState錯誤之後,舊客戶端值仍將顯示,而不是顯示數據庫中的新值?你能否就可能出現的問題提出建議?
感謝您的回覆,但可以檢查我的編輯。 –
@johnG:問題是視圖中的表單字段被當前的模型狀態填充,該狀態在重新加載'group'實體後沒有更新。你可以嘗試在'catch'塊的'ModelState.AddModelError(...)'行之前添加'ModelState.Clear()** **,看看它是否適合你? – Slauma
感謝您的幫助。它在添加ModelState.Clrea()後運行良好。但實際上我不明白爲什麼它不會工作,除非我清除模型狀態? –