views:

2277

answers:

3

Hi,

What is the point of an action returning ActionResult?

+1  A: 

ActionResult is the base class for many different types of controller results. By returning the base class, the controller action can return different types of results depending on the outcome of the method -- a ViewResult, a RedirectToActionResult, etc. ActionResult contains all of the data needed by the View or new Action that is the result of the current controller action.

tvanfosson
+1  A: 

Since it is the base class, it allows you to return any of the ActionResult subclasses, such as ViewResult or JsonResult. I typically return ViewResult as the default, but override that behavior if I am dealing with Ajax to return a JsonResult object.

This allows me to add Ajax as a progressive enhancement and keep the application working without JavaScript and without the need for separate controller actions.

Andrew Van Slaars
+10  A: 

Returning an ActionResult instead of "just doing whatever the ActionResult is doing" (i.e. using Response.Redirect directly or trying to render out a View through the Response OutputStream directly) gives you one really nice advantage: Unit Testing is really easy on that, especially since you normally do not need a web server to unit test MVC Projects.

Addendum: As an example for a redirect:

If you do

return Redirect(newUrl);

in your controller, your Unit Test can now

  • Verify that the return value is of Type "RedirectResult"
  • Look at the URL that is being redirected to by checking result.Url after casting it to RedirectResult
  • All without having to spin up IIS or trying to "clevery" intercept the Response.Redirect call
  • At the end of the day, RedirectResult calls Response.Redirect in it's ExecuteResult function, but your Controller Unit Test sits in front of that

Addendum 2: And while I am on it, here is an example of a Custom ActionResult:

http://www.stum.de/2008/10/22/permanentredirectresult/

This is just to show that they are not "Black Magic". They are actually pretty simple: Your Controller returns an Action Result, and the MVC Runtime will eventually call the ExecuteResult function on it, passing in a ControllerContext that your ActionResult can interact with. The whole point again is to separate the parts of M-V-C, to make Code Reusable, and to make Unit testing easier, or in short: To give a very clean Framework.

Michael Stum
ok so instead of doing Response.redirect, what how should I redirect? Using redirectToAction? what if the redirect is to a page that doesn't have an action? (say a .html page)
How about "Return Redirect(newUrl)"? That returns a RedirectResult, and result.Url contains the Url that is being redirected to. Internally, Redirect.Result calls the standard Response.Redirect, but for unit testing, it's much much easier.
Michael Stum
Added a more elaborate example to the answer.
Michael Stum