ViewBag、ViewData 和 TempData 属性

几种从 Action 传递数据到 View 的方式

我们经常需要在 Action 方法中传递数据到一个 View 中,MVC 框架为此提供了一些很方便的操作。下面简单简介几种常用的方式。

View Model 对象

通过 View Model 对象传递数据给View,这是最常用的一种,在 Acton 方法执行结束时通过 View 方法传递 View Model 对象给 View,如下代码所示:

... 
public ViewResult Index() { 
    DateTime date = DateTime.Now; 
    return View(date); 
} 

在 View 中我们通过 Model 属性来使用传递过来的 View Model 对象,如下:

复制代码
@model DateTime 

@{ 
    ViewBag.Title = "Index"; 
}

<h2>Index</h2> 
The day is: @Model.DayOfWeek
复制代码

在 Razor 视图引擎中,@model 的作用是声明 odel 属性的类型,省去了类型转换的麻烦,而 @Model 是V iew Model 对象的引用。

ViewBag、ViewData 和 TempData 属性

ViewBag、ViewData 和 TempData 都是 Controller 和 View 中能访问到的属性,都是用来存储小量的数据,他们的区别如下:

  • ViewBag,是一个动态(dynamic)的弱类型,在程序运行的时候解析,是 MVC3 中新增的特性,只在当前View有效。
  • ViewData,是一个字典集合,也是只在当前View有效,性能比 ViewBag 高,但是使用的时候需要类型转换。
  • TempData,也是字典集合,一般用于两个请求之间临时缓存内容或页面间传递消息,保存在 Session 中,使用完以后则从 Session 中被清除。

下面是三者使用的例子,先在 Controller 中分别用三者存储小数据:

复制代码
public class DerivedController : Controller {

    public ActionResult Index() {
        ViewBag.DayOfWeek = DateTime.Now.DayOfWeek;
        ViewData["DayOfMonth"] = DateTime.Now.Day;
        return View();
    }

    public ActionResult ProduceOutput() {
        TempData["Message"] = "Warning message from Derived Controller.";
        return Redirect("/Home/Index");
    }
}
复制代码

在 Views/Derived 目录下的 Index.cshtml 中,取出 ViewBag 和 ViewData 中的存储的数据:

...
Day of week from ViewBag: @ViewBag.DayOfWeek
<p /> 
Day of month from ViewData: @ViewData["DayOfMonth"] 

在 Views/Home 目录下的 Index.cshtml 中,取 TempData 中的数据如下:

...
@TempData["Message"]

当请求 /Derived/ProduceOutput 时,ProduceOutput 方法将一条消息存到 TempData 中,并跳转到 /Home/Index。

下面是分别是将URL定位到 /Derived/Index 和 /Derived/ProduceOutput 时的结果:

  

一般在当前 View 中使用 ViewBag 或 ViewData,在两个请求之间传递临时数据用 TempData。由于 TempData 被使用后即被释放,所以如果要二次使用 TempData 中的数据就需要将其存到其他变量中。

原文地址:https://www.cnblogs.com/DSC1991/p/13333806.html