Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between redirectToAction() and View()

Tags:

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

like image 254
Sanjeev Avatar asked Apr 02 '11 04:04

Sanjeev


People also ask

What is the difference between redirect () and RedirectToAction () in MVC?

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.

How do I redirect a view?

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.

Can we pass model in RedirectToAction?

My Question - Can I pass student model in RedirectToAction? Since the route dictionary deals with objects, try changing the GetStudent action to accept an object and inside cast it to Student . Another option would be to serialize it using JSON when passing it from FillStudent .


1 Answers

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.

like image 51
Naraen Avatar answered Oct 11 '22 11:10

Naraen