Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Redirect and RedirectToAction in ASP.NET MVC?

Tags:

asp.net-mvc

What is the difference between Redirect and RedirectToAction other than their return type? When do we use each? Explanation with any real life scenario would help me greatly.

I was looking at Confusion between Redirect and RedirectToAction, but, to me, it looks like the answer is more specific towards handling id parameter and returning proper view.

like image 253
gmail user Avatar asked Aug 30 '12 14:08

gmail user


People also ask

What is the difference between return view and return redirect?

Return View doesn't make a new requests, it just renders the view without changing URLs in the browser's address bar. Return RedirectToAction makes a new request and the URL in the browser's address bar is updated with the generated URL by MVC.

What is redirect in MVC?

The RedirectToAction() method makes new requests and URL in the browser's address bar is updated with the generated URL by MVC. The Redirect() method also makes new requests and URL in the browser's address bar is updated, but you have to specify the full URL to redirect.

How redirect a specific view from controller in MVC?

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.


1 Answers

RedirectToAction lets you construct a redirect url to a specific action/controller in your application, that is, it'll use the route table to generate the correct URL.

Redirect requires that you provide a full URL to redirect to.

If you have an action Index on controller Home with parameter Id:

  1. You can use RedirectToAction("Index", "Home", new { id = 5 }) which will generate the URL for you based on your route table.

  2. You can use Redirect but must construct the URL yourself, so you pass Redirect("/Home/Index/5") or however your route table works.

  3. You can't redirect to google.com (an external URL) using RedirectToAction, you must use Redirect.

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.

Best Practices: 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 your route table changes.

like image 155
Omar Avatar answered Sep 23 '22 13:09

Omar