Sanjeev
Sanjeev

Reputation: 281

Difference between redirectToAction() and View()

As I am new to ASP.NET MVC can anybody tell me the difference between return RedirectToAction() and return View()?

Upvotes: 26

Views: 15396

Answers (4)

user632299
user632299

Reputation: 309

here is simplest explanation of rendering view in mvc.

Upvotes: 0

Willy David Jr
Willy David Jr

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

Aruni Godage
Aruni Godage

Reputation: 923

  1. Return View doesn't make a new requests, it just renders the view without changing URLs in the browser's address bar.
  2. Return RedirectToAction makes a new request and the URL in the browser's address bar is updated with the generated URL by MVC.
  3. Return 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.
  4. 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

Naraen
Naraen

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

Related Questions