原文链接
控制器动作返回一种叫做动作结果(Action Result)的东西。动作结果是控制器动作返回给浏览器请求的东西。
ASP.NET MVC框架支持六种标准类型的动作结果:
所有这些动作结果都继承自ActionResult基类。
在大多数情况下,控制器动作 ViewResult。例如,代码清单2中的Index()控制器动作返回了一个ViewResult。
代码清单2 – BookController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Controllers { public class BookController : Controller { public ActionResult Index() { return View(); } } }
当一个动作返回一个ViewResult,将会向浏览器返回HTML。代码清单2中的Index()方法向浏览器返回了一个名为Index.aspx的视图。
注意到代码清单2中的Index()动作并没有放回一个ViewResult()。而是调用了Controller基类的View()方法。通常情况下,你并不直接返回一个动作结果。而是调用Controller基类的下列方法之一:
因此,如果你想向浏览器返回一个视图,你可以调用View()方法。
ContentResult动作结果很特别。你可以使用ContentResult动作结果来将动作结果作为纯文本返回。举个例子,代码清单4中的Index()方法将消息作为了纯文本返回,而不是HTML。
代码清单4 – StatusController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApp.Controllers
{
public class StatusController : Controller
{
public ContentResult Index()
{
return Content("Hello World!");
}
}
}
当调用StatusController.Index()动作时,并没有返回一个视图。而是向浏览器返回了原始的文本“Hello World!”。
如果一个控制器动作返回了一个结果,而这个结果并非一个动作结果 – 例如,一个日期或者整数 – 那么结果将自动被包装在ContentResult中。举个例子,当调用代码清单5中的WorkController的Index()动作时,日期将自动作为一个ContentResult返回。
代码清单5 – WorkerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApp.Controllers
{
public class WorkController : Controller
{
public DateTime Index()
{
return DateTime.Now;
}
}
}
代码清单5中的Index()动作返回了一个DateTime对象。ASP.NET MVC框架自动将DateTime对象转换为一个字符串,并且将DateTime值包装在一个ContentResult中。浏览器将会以纯文本的方式收到日期和时间。
这篇教程的目的是为你介绍ASP.NET MVC中控制器、控制器动作以及控制器动作结果的概念。在第一部分,你学习了如何向ASP.NET MVC项目中添加新的控制器。接下来,你学习了控制器的公共方法是如何作为控制器动作暴露给全世界的。最后,我们讨论了动作结果的各种不同类型,这些动作结果可以从控制器动作中返回。特别地,我们讨论了如何从控制器动作中返回一个ViewResult、RedirectToActionResult和ContentResult。