Posted on 3/29/2020 10:24:39 PM by Admin

What is ActionResult

In all the articles ,I have used ActionResult while returning a view.But in reality a MVC View actually returns a ViewResult.

Now, the question arises then how we were capable of returning view even when return type was ActionResult.Leave this question for a moment and come to below scenarios.

For real world application client can be anyone.Meaning request to controller can come directly from browser via URL or UI or it may come from any javascript client like Jquery (Ajax).
  • A browser always expects a Html result back as response while
  • JavaScript most probably requires JSON response.

Now, with the single return type two different responses can't be send.And only because of the difference in return type ,you will end up creating two different methods for same purpose.It will cause duplicate code in your application.


        public ActionResult GetEmployees()
        {
            List employeeList = new List() {
                new Employee(){Id=1,Name="Michael",Gender="Male",Age=23},
                  new Employee(){Id=2,Name="John",Gender="Male",Age=26},
                    new Employee(){Id=3,Name="Lucy",Gender="female",Age=20},
                };
            return View(employeeList);
        }
        public ActionResult GetEmployeeList()
        {
            List employeeList = new List() {
                new Employee(){Id=1,Name="Michael",Gender="Male",Age=23},
                  new Employee(){Id=2,Name="John",Gender="Male",Age=26},
                    new Employee(){Id=3,Name="Lucy",Gender="female",Age=20},
                };
            return Json(employeeList,JsonRequestBehavior.AllowGet);
        }

To solve such problem in MVC ,we have ActionResult.

ActionResult is actually parent of all other result.And every other response type are derived from ActionResult.So,it can be used to return any response like JsonResult,ViewResult,ContentResult etc.

ActionResult
ActionResult

        public ActionResult GetEmployees()
        {
            string type = Request.QueryString["type"];
         
        List employeeList = new List() {
        new Employee(){Id=1,Name="Michael",Gender="Male",Age=23},
        new Employee(){Id=2,Name="John",Gender="Male",Age=26},
        new Employee(){Id=3,Name="Lucy",Gender="female",Age=20},
        };
        if(type=="Json")
        {
        return Json(employeeList, JsonRequestBehavior.AllowGet);
        }
        return View(employeeList);
        }

Now,As you can observe if anyone asks for json type JsonResult will be sent else ViewResult will be sent.

Action Result
ActionResult

Now I think you got your answer that how were we able to return View with ActionResult as return type.