Hi,
What is the point of an action returning ActionResult?
Hi,
What is the point of an action returning ActionResult?
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.
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.
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
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.