2013-07-13 46 views
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錯誤之後,舊客戶端值仍將顯示,而不是顯示數據庫中的新值?你能否就可能出現的問題提出建議?

回答

2

沒有Reload從數據庫中獲取的當前值:

//... 
catch (DbUpdateConcurrencyException ex) 
{ 
    var entry = ex.Entries.Single(); 
    entry.Reload(); 
    //... 
} 
return View(group); 
//... 

如果您在瀏覽器中點擊刷新它將重複發送POST請求。這就像再次點擊提交按鈕。只要您沒有瀏覽器表單中的當前值,您將再次遇到相同的併發異常。點擊Url上的Enter將發送一個GET請求,所以你的GET操作將被調用並且當前值被加載和顯示。

+0

感謝您的回覆,但可以檢查我的編輯。 –

+1

@johnG:問題是視圖中的表單字段被當前的模型狀態填充,該狀態在重新加載'group'實體後沒有更新。你可以嘗試在'catch'塊的'ModelState.AddModelError(...)'行之前添加'ModelState.Clear()** **,看看它是否適合你? – Slauma

+0

感謝您的幫助。它在添加ModelState.Clrea()後運行良好。但實際上我不明白爲什麼它不會工作,除非我清除模型狀態? –