Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc RedirectToAction("Index") vs Index()

Say I have a controller with an Index Method and a Update Method. After the Update is done I want to redirect to Index(). Should I use return RedirectToAction("Index") or can I just call return Index()? Is there a difference?

public ActionResult Index()
{
  return View("Index", viewdata);
}

public ActionResult Update()
{
  // do updates
  return RedirectToAction("Index"); or
  return Index();
}
like image 406
terjetyl Avatar asked Nov 29 '08 03:11

terjetyl


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.

What is RedirectToAction MVC?

RedirectToAction(String, Object) Redirects to the specified action using the action name and route values. RedirectToAction(String, String) Redirects to the specified action using the action name and controller name.

What is the difference between return view and return redirect?

return RedirectToAction()To redirect to a different action which can be in the same or different controller. It tells ASP.NET MVC to respond with a browser to a different action instead of rendering HTML as View() method does. Browser receives this notification to redirect and makes a new request for the new action.

How do I use RedirectToAction?

The RedirectToAction() MethodThis 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.


2 Answers

Use the redirect otherwise the URL on the client will remain the same as the posted URL instead of the URL that corresponds to the Index action.

like image 64
tvanfosson Avatar answered Sep 21 '22 17:09

tvanfosson


Other things to consider:

  • Redirect action after a POST will act more nicely when the user clicks Refresh button, since they won't be prompted to resend data to server.

  • Form data will be lost with the redirect action unless you maintain them explicitly through, say, TempData. Without doing this, your form controls won't have any value after a POST, which may be undesirable in some cases.

like image 24
Buu Nguyen Avatar answered Sep 20 '22 17:09

Buu Nguyen