【问题标题】:Proper way to handle user resubmit for Delete Action?处理用户重新提交删除操作的正确方法?
【发布时间】:2011-01-31 23:39:27
【问题描述】:

假设用户删除了一条记录,然后按下返回箭头,并重新提交 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();
        }
    }

【问题讨论】:

  • 向他显示他要删除的内容不存在/已删除的通知。 :)
  • 如何在 MVC 中完成 UI?

标签: asp.net-mvc error-handling asp.net-mvc-3 crud


【解决方案1】:

处理此问题的 RESTFul 方法是抛出 404 Not Found(因为用户试图删除不再存在的记录):

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.:那边的 TODO 评论不错 :-)

【讨论】:

    【解决方案2】:

    在这种情况下,您需要使用 TempData。

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

    然后您可以访问视图中的 TempData 以显示消息。更多详情请参考link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多