What are different ways of returning/rendering a view in ASP.NET MVC?

There are four different ways for returning/rendering a view in ASP.NET MVC as given below:

  1. Return View() – This tells MVC to generate HTML to be displayed for the specified view and sends it to the browser. This acts like as Server.Transfer() in ASP.NET WebForm.
  2. Return RedirectToAction() – This tells MVC to redirect to specified action instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified action. This acts like as Response.Redirect() in ASP.NET WebForm.
    Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and use the route table to generate the correct URL. RedirectToAction cause the browser to receive a 302 redirect within your application and gives you an easier way to work with your route table.
  3. Return Redirect() – This tells MVC to redirect to specified URL instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified URL. This also acts like as Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect.
    Moreover, Redirect also cause the browser to receive a 302 redirect within your application, but you have to construct the URLs yourself.
  4. Return RedirectToRoute() – This tells MVC to look up the specifies route into the Route table that is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction().

Note:

  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 requests and URL in the browser’s address bar is updated with the generated URL by MVC.
  3. Return Redirect also makes a new requests and URL in the browser’s address bar is updated, but you have to specify the full URL to redirect
  4. 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.
  5. RedirectToRoute redirects to a specific route defined in the Route table.
Tagged , . Bookmark the permalink.

Leave a Reply