65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP.NET MVC 中使用 TempData

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.07/5 (15投票s)

2014 年 6 月 16 日

CPOL

2分钟阅读

viewsIcon

166802

在之前的 ASP.NET MVC 教程中,我们讨论了在 ASP.NET MVC 中从 Controller 向 View 传递数据的不同可用选项。我们实现了使用 ViewBag 和 ViewData 在 ASP.NET MVC 应用程序中传递数据。现在,在本教程的这部分,我们将讨论第三个可

在之前的 ASP.NET MVC 教程中,我们讨论了在 ASP.NET MVC 中从 Controller 向 View 传递数据的不同可用选项。我们实现了使用 ViewBagViewData 在 ASP.NET MVC 应用程序中传递数据。现在,在本教程的这部分,我们将讨论第三个可用选项,即 TempData

TempData 在 ASP.NET MVC 中基本上是一个从 TempDataDictionary 派生的字典对象。与 ViewBagViewData 等选项不同,TempData 会保留到下一个 HTTP 请求,而这些选项仅保留在当前请求中。因此,TempData 可用于在 Controller Action 之间以及重定向之间维护数据。

注意: 就像 ViewData 一样,为了避免错误,也需要对 TempData 进行类型转换和空值检查。

让我们看看如何在实际场景中使用 TempData 将数据从一个 Controller Action 传递到另一个 Controller Action。

   //Controller Action 1 (TemporaryEmployee)
   public ActionResult TemporaryEmployee()
  {
                  Employee employee = new Employee
                  {
                          EmpID = "121",
                          EmpFirstName = "Imran",
                          EmpLastName = "Ghani"
                  };                   
                  TempData["Employee"] = employee;
                  return RedirectToAction("PermanentEmployee");
  }   
 
   //Controller Action 2(PermanentEmployee)
   public ActionResult PermanentEmployee()
  {
                 Employee employee = TempData["Employee"] as Employee;
                 return View(employee);
   }

如上例所示,我们将一个员工对象存储在 TempData 中,在 Controller Action 1(即 TemporaryEmployee)中,并在另一个 Controller Action 2(即 PermanentEmployee)中检索它。但是,如果我们尝试使用 ViewBagViewData 执行相同的操作,我们将会在 Controller Action 2 中获得 null 值,因为只有 TempData 对象才能在 Controller Action 之间维护数据。

关于 TempData 的一个重要事项是,它将内容存储在 Session 对象中。那么,有人可能会提出一个问题:“ASP.NET MVC 中的 TempData 和 Session 有什么区别?”或“为什么我们需要 TempData 字典对象?为什么不能直接使用 Session 对象?

ASP.NET MVC TempData 与 Session 的比较

虽然 ASP.NET MVC TempData 将其内容存储在 Session 状态中,但它会在 Session 对象之前被销毁。TempData 在下一个 HTTP 请求中使用后立即被销毁,因此不需要显式操作。如果使用 Session 对象来实现此目的,则需要显式销毁该对象。

它最适合以下场景:

  • 我们需要从当前请求到下一个请求保留数据。
  • 将错误消息传递到错误页面。

通过以上关于在 ASP.NET MVC 中使用 TempData 的讨论,我们已经成功涵盖了在 ASP.NET MVC 中从 Controller 向 View 传递数据的不同选项。希望读者对在 ASP.NET MVC 中使用 ViewBag、ViewData 和 TempData 有更好的理解。

上一篇:ASP.NET MVC 中的 ViewBag 和 ViewData

其他相关文章

文章 在 ASP.NET MVC 中使用 TempData 最初发表在 Web 开发教程上。

© . All rights reserved.