John M
John M

Reputation: 14668

ASP .NET MVC 3 - Handle errors that occur in ActionResult DeleteConfirmed

In a controller a error with Create/Edit ActionResult can be handled with a try-catch block with the error being displayed on the view (via ModelState.AddModelError).

Now I am trying something similar with the DeleteConfirmed ActionResult but there is no error appearing on the view page. The table I am trying to delete from should be complaining about deleting a foreign-key field value.

Should I RedirectToAction differently or add something else?

 [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            try
            {
                StatusList statuslist = db.Status.Find(id);
                db.Status.Remove(statuslist);
                db.SaveChanges();
            }
            catch (DataException dex)
            {
                ModelState.AddModelError("", dex.Message);
                return RedirectToAction("Delete");

            }
                return RedirectToAction("Index");

        }

Upvotes: 0

Views: 1575

Answers (1)

Iridio
Iridio

Reputation: 9271

If you do a redirect, you lost the ModelState. So you can do two things imo.

  1. Setting the error message in TempData["myerrorkey"] = dex.Message, so the message will "survive" for one redirect
  2. Change your method and, in case of error, return a View so that the model state is not wiped out during the redirect

Personally I will choose the first. so you can think also to implement TempData in case of a delete telling the user, in the index page, that everything went smooth.

Upvotes: 1

Related Questions