Friday, 1 June 2018

ActionResult in MVC

In the previous blog, I wrote about Differences between RenderBody() and RenderSection().
In this blog, we will see about ActionResult 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

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 :)

No comments:

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks