Reputation: 281
As I am new to ASP.NET MVC can anybody tell me the difference between return RedirectToAction()
and return View()
?
Upvotes: 26
Views: 15396
Reputation: 9131
As an addition to all answers above, if you are using Implementing Validation using Data Annotation, use return View()
instead of RedirectToAction()
.
Validation message will not work using RedirectToAction as it doesn't get the model that is not valid and your validation message will not show as well on your view.
Upvotes: 1
Reputation: 923
View
doesn't make a new requests, it just renders the view
without changing URLs in the browser's address bar.RedirectToAction
makes a new request and the URL in the browser's
address bar is updated with the generated URL by MVC.Redirect
also makes a new request and the URL in the browser's address
bar is updated, but you have to specify the full URL.RedirectToRoute
redirects to the specified route defined in the the
route table.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.
Upvotes: 17
Reputation: 3250
return View()
tells MVC to generate HTML to be displayed and sends it to the browser.
RedirectToAction()
tells ASP.NET MVC to respond with a Browser redirect to a different action instead of rendering HTML. The browser will receive the redirect notification and make another request for the new action.
An example ...
let's say you are building a form to collect and save data, your URL looks like SomeEntity/Edit/23
. In the Edit action you will do return View()
to render a form with input fields to collect the data.
For this example let's say that on successful save of the data you want to display the data that has been saved. After processing the user's submitted data, if you do something like a RedirectToAction("Index")
where Index is the action that will display the data. The browser will get a HTTP 302 (temporary redirect) to go to /SomeEntity/Index/23
.
Upvotes: 25