Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 78 - Different types of ActionResult in asp.net mvc

Suggested Videos 
Part 75 - RequireHttps attribute
Part 76 - ValidateInput attribute
Part 77 - Custom action filters

In this video, we will discuss different types of ActionResult objects that can be returned by an action method.



The following is the signature of a typical action method in a controller. Notice that, the return type is ActionResult. ActionResult is an abstract class and has several sub types.
public ActionResult Index()
{
    return View();
}



Here is the list of all sub-types of ActionResult.
subtypes of actionresult

I have used a tool called ILSpy, to list all the sub-types of ActionResult. To use the tool yourself, here are the steps
1. Navigate to http://ilspy.net
2. Click on "Download Binaries" button, and extract them to a folder.
3. Run ILSpy.exe which can be found in the folder, where you have extracted the binaries.
4. Click on File - Open From GAC
5. Type "System.Web.Mvc" in the search box. Select the Assembly and click Open
6. At this point System.Web.Mvc assmbly should be loaded into ILSpy. Expand System.Web.Mvc, then expand ActionResult and then expand "Derived Types". You should now be able to see all the derived types.

Why do we have so many sub-types?
An action method in a controller, can return a wide range of objects. For example, an action method can return
1. ViewResult
2. PartialViewResult
3. JsonResult
4. RedirectResult etc..

What should be the return type of an action method - ActionResult or specific derived type? 
It's a good practise to return specific sub-types, but, if different paths of the action method returns different subtypes, then I would return an ActionResult object. An example is shown below.
public ActionResult Index()
{
    if (Your_Condition)
        return View();            // returns ViewResult object
    else
        return Json("Data");  // returns JsonResult object
}

The following table lists 
1. Action Result Sub Types
2. The purpose of each sub-type
3. The helper methods used to retrun the specific sub-type
Different types of ActionResult in asp.net mvc

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.