MVC3中Action返回类型ActionResult在System.Web.Mvc命名空间中.这些包含在控制器中的方法,我们称为控制器中的 Action,比如:HomeController 中的 Index 方法就是一个 Action,这些 Action 的作用就是处理请求,然后返回对请求的处理结果。
ActionResult是一个抽象类, 在Action中返回的都是其派生类.下面是我整理的ASP.NET MVC 1.0 版本中提供的ActionResult派生类:
类名 | 抽象类 | 父类 | 功能 |
ContentResult | | | 根据内容的类型和编码,数据内容. |
EmptyResult | | | 空方法. |
FileResult | abstract | | 写入文件内容,具体的写入方式在派生类中. |
FileContentResult | | FileResult | 通过 文件byte[] 写入文件. |
FilePathResult | | FileResult | 通过 文件路径 写入文件. |
FileStreamResult | | FileResult | 通过 文件Stream 写入文件. |
HttpUnauthorizedResult | | | 抛出401错误 |
JavaScriptResult | | | 返回javascript文件 |
JsonResult | | | 返回Json格式的数据 |
RedirectResult | | | 使用Response.Redirect重定向页面 |
RedirectToRouteResult | | | 根据Route规则重定向页面 |
ViewResultBase | abstract | | 调用IView.Render() |
PartialViewResult | | ViewResultBase | 调用父类ViewResultBase 的ExecuteResult方法. 重写了父类的FindView方法. 寻找用户控件.ascx文件 |
ViewResult | | ViewResultBase | 调用父类ViewResultBase 的ExecuteResult方法. 重写了父类的FindView方法. 寻找页面.aspx文件 |
- public
class ActionResultController : Controller -
- {
-
- public
ActionResult Index() -
- {
-
- return
View(); -
- }
-
- public
ActionResult ContentResult() -
- {
-
- return
Content("Hi, 我是ContentResult结果"); -
- }
-
- public
ActionResult EmptyResult() -
- {
-
- //空结果当然是空白了!
-
- //至于你信不信,
我反正信了 -
- return
new EmptyResult(); -
- }
-
- public
ActionResult FileResult() -
- {
-
- var
imgPath = Server.MapPath("~/demo.jpg"); -
- return
File(imgPath, "application/x-jpg", "demo.jpg"); -
- }
-
- public
ActionResult HttpNotFoundResult() -
- {
-
- return
HttpNotFound("Page Not Found"); -
- }
-
- public
ActionResult HttpUnauthorizedResult() -
- {
-
- //未验证时,跳转到Logon
-
- return
new HttpUnauthorizedResult(); -
- }
-
- public
ActionResult JavaScriptResult() -
- {
-
- string
js = "alert(\"Hi, I'm JavaScript.\");"; -
- return
JavaScript(js); -
- }
-
- public
ActionResult JsonResult() -
- {
-
- var
jsonObj = new -
- {
-
- Id
= 1, -
- Name
= "小铭", -
- Sex
= "男", -
- Like
= "足球" -
- };
-
- return
Json(jsonObj, JsonRequestBehavior.AllowGet); -
- }
-
- public
ActionResult RedirectResult() -
- {
-
- return
Redirect("~/demo.jpg"); -
- }
-
- public
ActionResult RedirectToRouteResult() -
- {
-
- return
RedirectToRoute(new { -
- controller
= "Hello", action = "" -
- });
-
- }
-
- public
ActionResult ViewResult() -
- {
-
- return
View(); -
- }
-
- public
ActionResult PartialViewResult() -
- {
-
- return
PartialView(); -
- }
-
- //禁止直接访问的ChildAction
-
- [ChildActionOnly]
-
- public
ActionResult ChildAction() -
- {
-
- return
PartialView(); -
- }
-
- //正确使用ChildAction
-
- public
ActionResult UsingChildAction() -
- {
-
- return
View(); -
- }
-
- }