When do you use View() vs. RedirectToAction

2019-04-03 23:59发布

问题:

This existing question sums up the basics of my question. The best answers there tells the difference between the two methods. I am looking for guidelines as to which method to use.

In short, I have an action in a controller which process a form and then display the results of the processing. When should I use return View() as opposed to return RedirectToAction("FormResult")?

回答1:

You can really use either. Generally speaking, though, after a form is posted you want to redirect so that refreshing the page doesn't cause the form to repost. Sometimes, however, it's not feasible to copy state to the new page and your processing is idempotent so refresh wouldn't hurt anything.

It's not that there's a hard-and-fast rule. You kind of have to weigh the pros and the cons.



回答2:

I would venture to say there is a hard and fast rule (well as much as there can be) - the Post/Redirect/Get (PRG) pattern. The standard with MVC (and the html helpers actually expect you to use this pattern) is:

  1. post your data.
  2. If there is an error (i.e. ModelState.IsValid=false) then return View() otherwise return RedirectResult.

If there was an error the HTML helpers will actually look at the posted values to redisplay as opposed to what you pass them by View(model) - again because the PRG pattern is 'supposed' to be what happened.



回答3:

  1. Return View doesn't make a new requests, it just renders the view
  2. without changing URLs in the browser's address bar. Return
    RedirectToAction makes a new requests and URL in the browser's address bar is updated with the generated URL by MVC.
  3. Return Redirect also makes a new requests and URL in the browser's address bar is updated, but you have to specify the full URL to redirect
  4. Between RedirectToAction and Redirect, best practice is to use RedirectToAction for anything dealing with your application actions/controllers. If you use Redirect and provide the URL, you'll need to modify those URLs manually when you change the route table.
  5. RedirectToRoute redirects to the specifies route defined in the the Route table.