Part 78 - MVC中不同的ActionResult 类型

In this section, 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.


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












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值