Difference Between ViewResult() and ActionResult()
What is the difference between ViewResult()
and ActionResult()
in ASP.NET MVC?
public ViewResult Index()
{
return View();
}
public ActionResult Index()
{
return View();
}
Solution 1:
ActionResult is an abstract class that can have several subtypes.
ActionResult Subtypes
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
Resources
- What's the difference between ActionResult and ViewResult for action method? [ASP.NET Forums]
Solution 2:
ActionResult is an abstract class.
ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.
You declare it this way so you can take advantage of polymorphism and return different types in the same method.
e.g:
public ActionResult Foo()
{
if (someCondition)
return View(); // returns ViewResult
else
return Json(); // returns JsonResult
}
Solution 3:
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
Solution 4:
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.
Solution 5:
While other answers have noted the differences correctly, note that if you are in fact returning a ViewResult only it is better to return the more specific type rather than the base ActionResult type. An obvious exception to this principle is when your method returns multiple types deriving from ActionResult.
For a full discussion of the reasons behind this principle please see the related discussion here: Must ASP.NET MVC Controller Methods Return ActionResult?