开发者

Proper way to handle user resubmit for Delete Action?

开发者 https://www.devze.com 2023-02-07 15:19 出处:网络
Suppose a user deletes a record, and then presses the back arrow, and resubmits the POST request. What are my options in handling this scenario?

Suppose a user deletes a record, and then presses the back arrow, and resubmits the POST request.

What are my options in handling this scenario?

What is preferred?

 [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.SaveCh开发者_C百科anges();

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


A RESTFul way to handle this is to throw a 404 Not Found (because the user tried to delete a record that no longer exists):

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

Another way is to add an error into the model state and redisplay the view:

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

and inside the view you would have a validation summary or a validation message for id to display the message.

P.S.: Nice TODO comment over there :-)


You'd want to make use of TempData in this case.

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

}

You can then access the TempData in the view to display the message. Refer this link for more details

0

精彩评论

暂无评论...
验证码 换一张
取 消