ctionResult及其子类的对照表 2010-07-09 17:06
我们所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件。而它的返回类型是ActionResult如
public ActionResult Index() { return View(); }除了View()之外那我们这里还能用于返回什么值呢?
场景:要返回代码片断,比如Ajax返回一个子页
我们先新建一个Action
public ActionResult Ascx() { return PartialView(); }我们下面再建一个View,仍然是在Action中点右键,AddView。
注意图中勾选。
于是新建了一个ascx页,我们将之少做改写一下
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <div> 得到一个DIV </div>运行,得到页面
除了上述情况,有时我们还会仅返回一段文本。
此时我们可以使用以下Action形式:
public ActionResult Text(){ return Content("这是一段文本"); }有时我们在调用Ajax时还会要求返回对象为Json序列化的结果,如:
public ActionResult ShowJson() { var m = new EiceIndexModel { Name = "邹健", Sex = true }; return Json(m); }返回文本:
{"Name":"邹健","Sex":true}大多时候js文件都是静态的,但有时js文件可能也要动态生成这时我们可以这样输出
public ActionResult Js() { return JavaScript("var x=0;"); }我们访问之,得到一个正常页面但其Content-Type:application/x-javascript; charset=utf-8
1.跳转到Url
public ActionResult rdurl() { return Redirect("http://www.baidu.com"); }2.跳转到Action
public ActionResult rdaction() { return RedirectToAction("Index","Eice"); }3.跳转到Routing规则
public ActionResult rdrouting() { return RedirectToRoute("Default",//Route名 new{ Controller = "Eice", Action = "Index" }); }
ActionResult的子类名称
说明
ViewResult
表示HTML的页面内容
EmptyResult
表示空白的页面内容
RedirectResult
表示定位到另外一个URL
JsonResult
表示可以运用到AJAX程序中JSON结果
JavaScriptResult
表示一个JavaScript对象
ContentResult
表示一个文本内容
FileContentResult
表示一个可以下载的、二进制内容的文件
FilePathResult
表示一个可以下载的、指定路径的文件
FileStreamResult
表示一个可以下载的、流式的文件
通过我们在代码中编写,不难看到如下的一段代码:
public ActionResult Index()
{
return View();
}
可能有人会有疑问,既然我定义的是ActionResult,为什么返回值会是View呢?
其实这个View的类型是ActionResult的子类ViewResult,有关Controller中的方法与返回对象请参照下表:
Controller中的方法
返回对象
View
ViewResult
Redirect
RedirectResult
RedirectToAction
RedirectToActionResult
RedirectToRoute
RedirectToRouteResult
Json
JsonResult
JavaScriptResult
JavaScriptResult
Content
ContentResult
File
FileContentResult、FilePathResult、FileStreamResult
