ActionResult 派生出以下子类:
- ViewResult
返回一个网页视图
- PartialViewResult
返回一个网页视图,但不适用布局页。
- ContentResult
返回一段字符串文本。和直接返回string字符串没有区别,只不过可以设置返回内容的格式和编码格式。例如:
public string Content()
{
return "<h1>HelloKitty</h1>"; //浏览器显示 HelloKitty
}
public ActionResult Content2()
{
//return Content("<h1>GoodbyeKitty</h1>"); //浏览器显示 GoodbyeKitty
//指定返回文本的格式与字符编码
return Content("<h1>GoodbyeKitty</h1>",
"text/html",System.Text.Encoding.UTF8);
}
- JsonResult
传入一个任意类型的对象,尽可能地将它格式化为JSON格式。
对于文件或图片类型数据会转换为乱码。
Dictionary这种键值对类型会被转换成js类,List这类会被转换成js数组
例如:
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
public ActionResult JSON1()
{
var array = new List<Student>();
array.Add(new Student { Name = "小明", Age = 12 });
array.Add(new Student { Name = "小李", Age = 15 });
return Json(array,JsonRequestBehavior.AllowGet);
//JsonRequestBehavior用于指定是否允许GET方式访问,默认只允许POST
//运行结果:[{"Name":"小明","Age":12},{"Name":"小李","Age":15}]
}
public ActionResult JSON2()
{
//也可使用匿名内部类来保存数据
return Json(new { name = "test", age = 16, sex = "boy" }, JsonRequestBehavior.AllowGet);
//运行结果:{"name":"test","age":16,"sex":"boy"}
}
- JavaScriptResult
返回一个JavaScript代码字符串。JavaScript()的效果实际上和Content()是一样的,只不过JavaScript()会自动指定返回文本的内容是application/x-javascript。例如:
public ActionResult JS()
{
return JavaScript("alert('" + DateTime.Now.ToLongTimeString() + "')");
}
public ActionResult JS2()
{
return Content("alert('" + DateTime.Now.ToLongTimeString() + "')", "application/x-javascript");
//这样写效果和上面完全是一样的
}
/*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://localhost:5695/home/js2"></script>
<!--可以直接在script标签中填写action的地址-->
</head>
<body></body>
</html>
*/
- FileResult
返回一个文件,可以通过文件名、文件流、二进制Byte[ ]的形式发送文件,需要指定文件类型。例如:
public ActionResult FILE1()
{
System.IO.Stream fs = System.IO.File.OpenRead(@"test.png");
return File(fs, @"image/png"); //通过流的方法
}
public ActionResult FILE2()
{
return File(@"test.png", @"image/png"); //通过文件名的方式
}
public ActionResult FILE3()
{
System.Drawing.Bitmap b = new System.Drawing.Bitmap(100, 100); //创建一张空白图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] bytes = ms.GetBuffer();
return File(bytes, @"image/bmp"); //通过二进制数据的方式
}
/*
//现在可以直接将地址赋值给img标签来进行显示了
<img src="http://localhost:5695/home/file1" alt="">
*/
- EmptyResult
返回null,如果Action返回null,则会自动将null转换为EmptyResult
- RedirectResult
使客户端浏览器跳转到指定的URL
- RedirectToRouteResult
RedirectToAction()方法将客户端浏览器跳转的指定的Action
RedirectToRoute()方法将客户端浏览器跳转到指定的URL,取决于路由
附录:MIME
MIME (Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。
是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。
常见文件格式
文件类型 | 格式编码 |
超文本标记语言文件(.html) | text/html |
XML文档(.xml) | Text/xml |
普通文本(.txt) | Text/plain |
PDF文档(.pdf) | application/pdf |
Word文档(.docx) | application/msword |
PNG图像(.png) | image/png |
GIF图形(.gif) | image/gif |
JPEG图形(.jpeg , .jpg) | image/jpeg |