learning
learning

Reputation: 11725

How to pass errors from one action to another

How can I pass the modelstate errors from oneaction to another in the case of the Action Delete?

  public ActionResult Index()
    {
        ProjectTestModel model = new ProjectTestModel ();
        return GetProjectView(model);

    }

    public ActionResult GetProjectView(ProjectTestModel model)
    {
        return View("Index", model);
    }

 public ActionResult Delete(int id)
    {
        try
        {
           test.Load(id)
            test.Delete();
            return RedirectToAction("Index");
        }

        catch (Exception e)
        {
            ModelState.AddModelError("Error", e.Message);
            return RedirectToAction("Index");
        }
    }

Upvotes: 3

Views: 1524

Answers (2)

David Glenn
David Glenn

Reputation: 24522

It is common to return the view on error and redirect when successful.

public ActionResult Delete(int id)
{
    try
    {
        test.Load(id);
        test.Delete();
        return RedirectToAction("Index");
    }

    catch (Exception e)
    {
        ModelState.AddModelError("Error", e.Message);
        return View("Index");
    }
}

Upvotes: 2

Alexander Prokofyev
Alexander Prokofyev

Reputation: 34515

You may consider using TempData to pass an error message.

Upvotes: 4

Related Questions