一、定义

MVC中ActionResult是Action的返回结果。ActionResult 有多个派生类,每个子类功能均不同,并不是所有的子类都需要返回视图View,有些直接返回流,有些返回字符串等。ActionResult是一个抽象类,它定义了唯一的ExecuteResult方法,参数为一个ControllerContext,下面为您介绍MVC中的ActionResult 的用法

二、什么是ActionResult

ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的 是非ActionResult类型,控制器将会将结果转换为一个ContentResult类型。默认的ControllerActionInvoker 调用ActionResult.ExecuteResult方法生成应答结果。

三、常见的ActionResult

1、ViewResult

表示一个视图结果,它根据视图模板产生应答内容。对应得Controller方法为View。

2、PartialViewResult

表示一个部分视图结果,与ViewResult本质上一致,只是部分视图不支持母版,对应于ASP.NET,ViewResult相当于一个Page,而PartialViewResult 则相当于一个UserControl。它对应得Controller方法的PartialView.

3、RedirectResult

表示一个连接跳转,相当于ASP.NET中的Response.Redirect方法,对应得Controller方法为Redirect。

4、RedirectToRouteResult

同样表示一个跳转,MVC会根据我们指定的路由名称或路由信息(RouteValueDictionary)来生成Url地址,然后调用Response.Redirect跳转。对应的Controller方法为RedirectToAction和RedirectToRoute.

5、ContentResult

返回简单的纯文本内容,可通过ContentType属性指定应答文档类型,通过ContentEncoding属性指定应答文档的字符编码。可通过Controller类中的Content方法便捷地返回ContentResult对象。如果控制器方法返回非ActionResult对象,MVc将简单地以返回对象的toString()内容为基础产生一个ContentResult对象。

6、EmptyResult

返回一个空的结果,如果控制器方法返回一个null ,MVC将其转换成EmptyResult对象。

7、JavaScriptResult

本质上是一个文本内容,只是将Response.ContentType设置为application/x-javascript,此结果应该和MicrosoftMvcAjax.js脚本配合使用,客户端接收到Ajax应答后,将判断Response.ContentType的值,如果是application/x-javascript,则直接eval 执行返回的应答内容,此结果类型对应得Controller方法为JavaScript.

8、JsonResult

表示一个Json结果。MVC将Response.ContentType 设置为application/json,并通过JavaScriptSerializer类指定对象序列化为Json表示方式。需要注意,默认情况下,Mvc不允许GET请求返回Json结果,要解除此限制,在生成JsonResult对象时,将其JsonRequestBehavior属性设置为JsonRequestBehavior.AllowGet,此结果对应Controller方法的Json.

9、FileResult(FilePathResult、FileContentResult、FileStreamResult)

这三个类继承于FileResult,表示一个文件内容,三者区别在于,FilePath 通过路径传送文件到客户端,FileContent 通过二进制数据的方式,而FileStream 是通过Stream(流)的方式来传送。Controller为这三个文件结果类型提供了一个名为File的重载方法。

FilePathResult: 直接将一个文件发送给客户端

FileContentResult: 返回byte字节给客户端(比如图片)

FileStreamResult: 返回流

10、HttpUnauthorizedResult

表示一个未经授权访问的错误,MVC会向客户端发送一个401的应答状态。如果在web.config 中开启了表单验证(authenication mode=”Forms”),则401状态会将Url 转向指定的loginUrl 链接。

11、HttpStatusCodeResult

返回一个服务器的错误信息

12、HttpNoFoundResult

返回一个找不到Action错误信息

四、ActionResult子类之间的关系表

五、ActionResult(12种)的简单应用

源码:

using StudyMVC4.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;

namespace StudyMVC4.Controllers
{
    public class HomeController : Controller
    {
       
        public ActionResult Index() {
            return View();
        }

/// <summary>
        /// ContentResult用法(返回文本)
        /// http://localhost:30735/home/ContentResultDemo
        /// </summary>
        /// <returns>返回文本</returns>
        public ActionResult ContentResultDemo(){ 
            string str = "ContentResultDemo!";
            return Content(str);
        }

/// <summary>
        /// EmptyResult的用法(返回空对象)
        /// http://localhost:30735/home/EmptyResultDemo
        /// </summary>
        /// <returns>返回一个空对象</returns>
        public ActionResult EmptyResultDemo (){ 
            return new EmptyResult();
        }

/// <summary>
        /// FileContentResult的用法(返回图片)
        /// http://localhost:30735/home/FileContentResultDemo
        /// </summary>
        /// <returns>显示一个文件内容</returns>
        public ActionResult FileContentResultDemo() {
            FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
            fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
            string contentType = "image/jpeg";
            return File(buffer, contentType);
        }
      
        /// <summary>
        /// FilePathResult的用法(返回图片)
        /// http://localhost:30735/home/FilePathResultDemo/002
        /// </summary>
        /// <param name="id">图片id</param>
        /// <returns>直接将返回一个文件对象</returns>
        public FilePathResult FilePathResultDemo(string id)
        {
            string path = Server.MapPath(@"/Images/"+id +".jpg");
            //定义内容类型(图片)
            string contentType = "image/jpeg"; 
            //FilePathResult直接返回file对象
            return File(path, contentType);
        }

/// <summary>
        /// FileStreamResult的用法(返回图片)
        /// http://localhost:30735/home/FileStreamResultDemo
        /// </summary>
        /// <returns>返回文件流(图片)</returns>
        public ActionResult FileStreamResultDemo()
        {
            FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
            string contentType = "image/jpeg";
            return File(fs, contentType);
        }

/// <summary>
        /// HttpUnauthorizedResult 的用法(抛出401错误)
        /// http://localhost:30735/home/HttpUnauthorizedResult
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpUnauthorizedResultDemo()
        {
            return new HttpUnauthorizedResult();
        }

/// <summary>
        /// HttpStatusCodeResult的方法(返回错误状态信息)
        ///  http://localhost:30735/home/HttpStatusCodeResult
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpStatusCodeResultDemo() {
            return new HttpStatusCodeResult(500, "System Error");
        }

/// <summary>
        /// HttpNotFoundResult的使用方法
        /// http://localhost:30735/home/HttpNotFoundResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult HttpNotFoundResultDemo() {
            return new HttpNotFoundResult("not found action");
        }

/// <summary>
       /// JavaScriptResult 的用法(返回脚本文件)
        /// http://localhost:30735/home/JavaScriptResultDemo
       /// </summary>
       /// <returns>返回脚本内容</returns>
        public ActionResult JavaScriptResultDemo()
        {
            return JavaScript(@"<script>alert('Test JavaScriptResultDemo!')</script>");
        }

/// <summary>
        /// JsonResult的用法(返回一个json对象)
        /// http://localhost:30735/home/JsonResultDemo
        /// </summary>
        /// <returns>返回一个json对象</returns>
        public ActionResult JsonResultDemo()
        {
            var tempObj = new { Controller = "HomeController", Action = "JsonResultDemo" };
            return Json(tempObj);
        }

/// <summary>
        /// RedirectResult的用法(跳转url地址)
        /// http://localhost:30735/home/RedirectResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectResultDemo()
        {
            return Redirect(@"http://wwww.baidu.com");
        }

/// <summary>
        /// RedirectToRouteResult的用法(跳转的action名称)
        /// http://localhost:30735/home/RedirectToRouteResultDemo
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectToRouteResultDemo()
        {
            return RedirectToAction(@"FileStreamResultDemo");
        }

/// <summary>
        /// PartialViewResult的用法(返回部分视图)
        /// http://localhost:30735/home/PartialViewResultDemo
        /// </summary>
        /// <returns></returns>
        public PartialViewResult PartialViewResultDemo()
        {
            return PartialView();
        }

/// <summary>
       /// ViewResult的用法(返回视图)
        ///  http://localhost:30735/home/ViewResultDemo
       /// </summary>
       /// <returns></returns>
        public ActionResult ViewResultDemo()
        {
            //如果没有传入View名称, 默认寻找与Action名称相同的View页面.
            return View();
        }
    }
}

PS:源码及文档下载地址:http://pan.baidu.com/s/1boRRUGZ

平时多记记,到用时才能看看,记录你的进步,分享你的成果

MVC中几种常用的ActionResult的更多相关文章

  1. MVC中几种常用ActionResult

    一.定义 MVC中ActionResult是Action的返回结果.ActionResult 有多个派生类,每个子类功能均不同,并不是所有的子类都需要返回视图View,有些直接返回流,有些返回字符串等 ...

  2. [转]MVC中几种常用ActionResult

    本文转自:http://www.cnblogs.com/xielong/p/5940535.html 一.定义 MVC中ActionResult是Action的返回结果.ActionResult 有多 ...

  3. asp.net mvc 中 一种简单的 URL 重写

    asp.net mvc 中 一种简单的 URL 重写 Intro 在项目中想增加一个公告的功能,但是又不想直接用默认带的那种路由,感觉好low逼,想弄成那种伪静态化的路由 (别问我为什么不直接静态化, ...

  4. Java中几种常用数据类型之间转换的方法

    Java中几种常用的数据类型之间转换方法: 1. short-->int 转换 exp: short shortvar=0; int intvar=0; shortvar= (short) in ...

  5. DotNet中几种常用的加密算法

    在.NET项目中,我们较多的使用到加密这个操作.因为在现代的项目中,对信息安全的要求越来越高,那么多信息的加密就变得至关重要.现在提供几种常用的加密/解密算法. 1.用于文本和Base64编码文本的互 ...

  6. Asp.net MVC 中Controller返回值类型ActionResult

    [Asp.net MVC中Controller返回值类型] 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必 ...

  7. 【Android 界面效果28】Android应用中五种常用的menu

    Android Menu在手机的应用中起着导航的作用,作者总结了5种常用的Menu. 1.左右推出的Menu 前段时间比较流行,我最早是在海豚浏览器中看到的,当时耳目一新.最早使用左右推出菜单的,听说 ...

  8. MVC中的扩展点(六)ActionResult

    ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的是非ActionResult类型,控制器将会将结果转换为 ...

  9. MVC 中Controller返回值类型ActionResult

    下面列举Asp.net MVC中Controller中的ActionResult返回类型 1.返回ViewResult视图结果,将视图呈现给网页 public ActionResult About() ...

随机推荐

  1. SSH Key的生成和使用(for git)

    SSH Key的生成和使用 一.总结 1.用git base生成ssh,会生成id_rsa.pub文件,还有一个私钥文件.     $ ssh-keygen -t rsa -C “youremailn ...

  2. nyoj--914--Yougth的最大化(二分查找)

    Yougth的最大化 时间限制:1000 ms  |  内存限制:65535 KB 难度:4 描述 Yougth现在有n个物品的重量和价值分别是Wi和Vi,你能帮他从中选出k个物品使得单位重量的价值最 ...

  3. 乔治·霍兹(George Hotz):特斯拉、谷歌最可怕的对手!

    17岁破解iPhone,21岁攻陷索尼PS3:现在,他是埃隆·马斯克最可怕的对手.   黑客往事   许多年后,当乔治·霍兹(George Hotz)回首往事,一定会把2007年作为自己传奇人生的起点 ...

  4. SSRS参数不能默认全选的解决方法

    解决方法选自<SQL Server 2008 R2 Reporting Services 报表服务>一书,亲测有效. 注意:参数默认值如果是字符串需要类型转换 =CStr("AL ...

  5. APACHE KYLIN™ 概览(分布式分析引擎)

    Apache Kylin™是一个开源的分布式分析引擎,提供Hadoop/Spark之上的SQL查询接口及多维分析(OLAP)能力以支持超大规模数据,最初由eBay Inc. 开发并贡献至开源社区.它能 ...

  6. sql server 中文乱码

    在数据库中查询每个字段的备注信息(备注信息是用中文写的),查询结果却是乱码,如图: 百度说需要设置数据库的排序规则,设置成中文的,结果还是报5030错误,无法修改字符集为Chinese_PRC_CI_ ...

  7. js函数 DOM操作

    回学校了两天请了两天假,数组和方法的内容周末一定补上! 今天介绍一下JavaScript函数 Function 一.基础内容 1.定义 函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块. f ...

  8. iOS开发——循环遍历的比较

    常用的有for in.for循环.EnumerateObjectsUsingBlock 1.小规模的数据无所谓,但是对大量数据,for in 的遍历速度非常之快,不是for循环能比的: 2.对于数组, ...

  9. c++PrimerChap8IO库

    #include<iostream> #include<fstream> #include<string> using namespace std; int mai ...

  10. man 7 glob

    GLOB(7) Linux Programmer's Manual GLOB(7) NAME glob - 形成路径名称 描述 (DESCRIPTION) 很久以前 在 UNIX V6 版 中 有一个 ...