Thursday, July 10, 2014

Difference Between ViewResult() and ActionResult()

public ViewResult Index()
{
    return View();
}

public ActionResult Index()
{
    return View();
}
ActionResult is an abstract class that can have several subtypes.
ActionResult Subtypes Resources
public ActionResult Foo() { if (someCondition) return View(); // returns ViewResult else return Json(); // returns JsonResult }
ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
  • ViewResult - Renders a specifed view to the response stream
  • PartialViewResult - Renders a specifed partial view to the response stream
  • EmptyResult - An empty response is returned
  • RedirectResult - Performs an HTTP redirection to a specifed URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  • JsonResult - Serializes a given ViewData object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - Writes content to the response stream without requiring a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - Returns a file to the client, which is provided by a Stream
  • FilePathResult - Returns a file to the client
ActionResult is an abstract class.
ViewResult derives from ActionResult. Other derived classes include JsonResult andPartialViewResult.
You declare it this way so you can take advantage of polymorphism and return different types in the same method.
e.g:
ActionResult is an abstract class, and it's base class for ViewResult class.
In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.
And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.
It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.

No comments:

Post a Comment