Results in MVC

From Logic Wiki
Jump to: navigation, search


What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so on.

“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

public ActionResult DynamicView(bool IsHtmlView)
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}

What are the different types of results in MVC?

Note:-It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest. There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that can have 11 subtypes’sas listed below: -

# ViewResult - Renders a specified view to the response stream
#  PartialViewResult - Renders a specified partial view to the response stream
#  EmptyResult - An empty response is returned
#  RedirectResult - Performs an HTTP redirection to a specified 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 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