2011-01-31 25 views
1

假設用戶刪除一條記錄,然後按下後退箭頭,然後重新提交POST請求。處理用戶重新提交刪除操作的正確方法?

我在處理這種情況時有什麼選擇?

什麼是首選?

[HttpPost] 
    public ActionResult Delete(string EntryName, Guid id, FormCollection collection) 
    { 
     try 
     { 
      var ret = from m in _entities.MyList 
         where m.MyListID == id 
         && m.EntryName == EntryName 
         select m ; 

      if (ret.Count() == 0) 
      { 
       // This happens if the user pressed the back button and resubmitted 
       // todo: ask SO what is the best way to approach this... 
       // User feedback? How? 
       return RedirectToAction("Index", new { id = id }); 
      } 

      _entities.DeleteObject(ret.FirstOrDefault()); 
      _entities.SaveChanges(); 

      return RedirectToAction("Index", new { id = id }); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 
+0

那邊尼斯TODO註釋顯示給他的通知,他試圖刪除不存在什麼/已被刪除。 :) – 2011-01-31 23:41:00

回答

2

一個RESTful的方式來處理,這是拋出一個404未找到(因爲用戶試圖刪除不再存在的記錄):

if (ret.Count() == 0) 
{ 
    throw new HttpException(404, "Not found"); 
} 

另一種方法是增加錯誤到模型狀態並重新顯示視圖:

if (ret.Count() == 0) 
{ 
    ModelState.AddModelError("id", "An item with the specified id was not found"); 
    return View(); 
} 

和視圖內你將有一個驗證摘要或id一個驗證消息,以顯示消息。

P.S::-)

0

你會想利用的TempData在這種情況下。

if (ret.Count() == 0) 
{ 
    TempData["ErrorMessage"] = "Record <Number> does not exist"; 
    return RedirectToAction("Index"); 

} 

然後,您可以訪問視圖中的TempData以顯示消息。請參閱本link瞭解更多詳情

相關問題