Home
Do you use RedirectToAction instead of returning a view that’s not named the same as the action?
  v1.0 Posted at 8/03/2013 5:36 AM by Tiago Araujo

Returning a view that is named differently to the action confuses the MVC process and can make the code difficult to maintain.

In cases where data is posted, if you don't do a redirect and the user hits the refresh/reload button in the browser, the data can be is submitted more than once. This can lead to duplicate data being stored in your database.

Redirecting after posted data has been processed is called the Post-Redirect-Get (or PRG) pattern.

[HttpPost]
public ActionResult Create(CreateModel model)
{
    // ... save to DB, then:
    ViewBag.Message = "Successfully created " + model.Name;
    return View("Success");
}

Figure: Bad Example – Returning a different view is misleading and potentially dangerous
[HttpPost]
public ActionResult Create(CreateModel model)
{
    // ... save to DB, then:
    return RedirectToAction("Success", new { message = "Successfully created " + model.Name });
}

public ActionResult Success(string message)
{
    ViewBag.Message = message;
    return View();
}

Figure: Good Example – Using the PRG pattern to avoid duplicate data being posted

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.