Why Do We Have Multiple Types Of Results In MVC?

ActionResult is nothing but a base result class or an abstract parent class. As we know, an MVC architecture follows a request/response process, so the Browser/client will request the Service or the data from the Server and the Server will give a response. Thus, the client can request any type/format of the data like it will request HTML, JSON, JavaScript, binary etc.

Thus, MVC framework provides a valuable Type as ActionResult, which will take care of mostly all types of results.

MVC framework provides some Action Results like:

ActionResult Helper Method Description
ViewResult View ViewResult renders a view as a web page.
PartialViewResult PartialView PartialViewResult renders the partial view.
RedirectResult Redirect When you want to redirect to another action method, we will use RedirectResult.
RedirectToRouteResult RedirectToRoute Redirect to another action method.
ContentResult Content Returns a user-defined content type.
JsonResult Json It is used when you want to return a serialized JSON object.
JavaScriptResult JavaScript Returns a script that can be executed on the client.
FileResult File Returns a binary output to write to the response.
EmptyResult (None) Returns a null result.

If your requirement is not fulfilled by these inbuilt Action Results, you can create your own custom ActionResult, which we will discuss later.

Thus, we have one question. As we can see in our real time project, we are using basically ActionResult as a return type instead mentioning any specific ResultType like JsonResult,ViewResult etc. Why?

ActionResult is a base class of all the  inbuilt Result classes. All the mentioned classes are inherited from ActionResult. Thus, we are using the concept of Runtime Polymorphism, where a base class object can point to its child class. Thus, if we are mentioning ActionResult as a return type of any action/function and it returns any child class (viewresult,jsonresult ), it will automatically type cast to the parent class type, i.e., “ActionResult”.

 
Example 1

  1. Public ActionResult index() {  
  2.     Return view();  
  3.     à here we are returning view(viewresult) instead of ActionResult.So with  
  4.     the help of polymorphism it will automatically type casted to parent class.  
  5. }  

Example 2

You can declare it this way, so you can take advantage of Polymorphism and return different types in the same method.

  1. public ActionResult MyResult()  
  2. {  
  3.     if (someCondition) return View(); // returns ViewResult  
  4.     else return Json(); // returns JsonResult  
  5. }  
Next Recommended Reading Return Multiple Models to View In MVC