I'm new to MVC can anyone tell me what RedirectResult
is used for?
I'm was wondering what is the different between this:
public ActionResult Index() { return new RedirectResult("http://www.google.com"); }
and this:
public RedirectResult Index() { return new RedirectResult("http://www.google.com"); }
RedirectResult. RedirectResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header to the supplied URL. It will redirect us to the provided URL, it doesn't matter if the URL is relative or absolute.
ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.
The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response. Redirect() in ASP.NET WebForm.
It is used to perform an HTTP redirect to a given url. Basically it will send the 302 status code along with the Location header in the response so that the client now issues a new HTTP request to this new location.
Usually you would use it like this instead of explicitly calling the constructor:
public ActionResult Index() { return Redirect("http://www.google.com"); }
As far as the difference between your two code snippets is concerned, well, it's more C# question than MVC related. In fact RedirectResult derives from ActionResult so both are valid syntaxes. Personally I prefer the first one as you could for example decide to change this redirect to return a view:
public ActionResult Index() { return View(); }
and if you have explicitly specified that the return type is RedirectResult
instead of ActionResult
you would now have to modify it to ViewResult
(probably not a big deal but it's an additional step you have to do).
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