您的位置:首页 > 其它

Part 78 - MVC中不同的ActionResult 类型

2016-11-10 16:10 316 查看
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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: