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")
?
RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.
return RedirectToAction()To redirect to a different action which can be in the same or different controller. It tells ASP.NET MVC to respond with a browser to a different action instead of rendering HTML as View() method does. Browser receives this notification to redirect and makes a new request for the new action.
You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With