ActionResult in MVC


Controllers executes all incoming requests using Action method. An ActionMethod may return different type of result. In this blog, we will see about ActionResult of an ActionMethod in details.

So, What is ActionResult?


ActionResult is the base class for all action results in MVC.
Whenever you create a controller class, a default action is created like this -

In below code, Action type is ViewResult and View is a helper method

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

The above code can be written in an alternate way.

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

Different types of ActionResult in MVC

ActionResult Type
Helper Method
ViewResult
View()
PartialViewResult
PartialView()
RedirectResult
Redirect()
ContentResult
Content()
RedirectToRouteResult
RedirectToAction()
FileResult
File()
JsonResult
Json()


Below is the sample code to show different helper method -

public ActionResult Index()
        {
            return new EmptyResult();
        }

public ActionResult Index()
        {
            return Content("This is a Content");
        }

Consider below code- 

This will throw a compile time error -

Cannot implicitly convert type 'System.Web.Mvc.ContentResult' to 'System.Web.Mvc.EmptyResult' 

In below code, the return type is EmptyResult and value which is returning is of ContentResult type.

public EmptyResult Index()
        {
            return Content("This is a Content");
         }


If you will use ActionResult as return type then it will not throw any error as it is the base class for all type of action result.

So either use respective Result Type or use ActionResult for all returning helper method.

Hope it is clear to you, in case of any confusion open Visual Studio and try above-given code, you will get a clear picture about ActionResult.
Happy Learning :)


Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers