Action Results in MVC Views

It is very important to note that it is the controller’s job to tell the ASP.NET MVC Framework what it should do next, but not how to do it. This communication occurs through the use of +ActionResult+s, the return values which every controller action is expected to provide.

For example, when a controller decides to show a view, it tells the ASP.NET MVC Framework to show the view by returning a ViewResult. It does not render the view itself.

Despite the fact that every controller action needs to return an ActionResult, you will rarely be creating them manually. Instead, you’ll usually rely on the helper methods that the System.Web.Mvc.Controller base class provides, such as:

Returns a ContentResult that renders arbitrary text, e.g., “Hello, world!”

Returns a FileResult that renders the contents of a file, e.g., a PDF.

Returns an HttpNotFoundResult that renders a 404 HTTP status code response.

JavaScript():: Returns a JavaScriptResult
that renders JavaScript, e.g., “function hello() { alert(Hello, World!); }”.

Returns a JsonResult that serializes an object and renders it in JavaScript Object Notation (JSON) format, e.g., “{ “Message”: Hello, World! }”.

Returns a PartialViewResult that renders only the content of a view (i.e., a view without its layout).

Returns a RedirectResult that renders a 302 (temporary) status code to redirect the user to a given URL, e.g., “302”. This method has a sibling, RedirectPermanent(), that also returns a RedirectResult, but uses HTTP status code 301 to indicate a permanent redirect rather than a temporary one.

RedirectToAction() and RedirectToRoute()
Act just like the Redirect() helper, only the framework dynamically determines the external URL by querying the routing engine. Like the Redirect() helper, these two helpers also have permanent redirect variants: RedirectToActionPermanent() and RedirectToRoutePermanent().

Returns a ViewResult that renders a view.


You may also like...