makerofthings7
makerofthings7

Reputation: 61433

Proper way to handle user resubmit for Delete Action?

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.SaveChanges();

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

Upvotes: 1

Views: 268

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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 :-)

Upvotes: 2

WorldIsRound
WorldIsRound

Reputation: 1554

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

Upvotes: 0

Related Questions