public class EiceController : Controller { public ActionResult Index() { ViewData["ViewData"] = "在这里显示ViewData"; TempData["TempData"] = "在这里显示TempData"; return View(); } public ActionResult Index2() { return View("Index"); //这里指定了规定显示的View文件即Eice目录下的Index.aspx } }
我们将Index的参数移除,并提供了ViewData和TempData的赋值
在Views/Eice/Index.aspx这个View中我们写以下代码
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 1:<%=ViewData["ViewData"]%><br /> 2:<%=TempData["TempData"]%> </asp:Content>
注意上面的1.2不是行号,是我写的。
接下来我们运行工程
访问http://localhost/Eice/Index
可以看到运行得到以下
1.在这里显示ViewData 2.在这里显示TempData
再访问http://localhost/Eice/Index2
显示结果为
1. 2.在这里显示TempData
这里1显示是的ViewData中的内容,2为TempData传递的内容
我们可以看到ViewData只能在当前Action中有效
但是TempData可以类似于Session一样到其它页面仍然存在,但只限一页的访问(类似于Monorail中的Flash)
TempData一般用于临时的缓存内容或抛出错误页面时传递错误信息。
二、通过ViewData.Model来传递对象
我们先建立一个Model:EiceIndexModel.cs。
public class EiceIndexModel { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } /// <summary> /// 性别 /// </summary> public bool Sex { get; set; } }
之后我们建立一个新的Action:Index3
public ActionResult Index3(){ var m = new EiceIndexModel { Name = "邹健", Sex = true }; return View(m); }
我们下面为Index3建立View文件,仍然是在Index3上点击右键AddView
于是自动生成了一个View文件,我们运行看结果:
我们上边所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件。而它的返回类型是ActionResult如
public ActionResult Index() { return View(); }
除了View()之外那我们这里还能用于返回什么值呢?
一、ascx页面
场景:要返回代码片断,比如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("这是一段文本"); }
三、返回Json
有时我们在调用Ajax时还会要求返回对象为Json序列化的结果,如:
public ActionResult ShowJson() { var m = new EiceIndexModel { Name = "邹健", Sex = true }; return Json(m); }
返回文本:
{"Name":"邹健","Sex":true}
四、输出JS文件
大多时候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" }); }
六、显示文件
public ActionResult fn() { return File( "/Content/site.css"//文件路径 , "text/css"//文件类型 ); }
转载整理于:http://www.cnblogs.com/chsword/archive/2009/03/12/zd_mvc4.html