asp.net-mvc-2 - 在 ASP.NET MVC 2 中读取后仍保留 TempData

标签 asp.net-mvc-2 tempdata

在 ASP.NET MVC 2 中,TempData值一直存在,直到 session 结束或读取它们为止。在 words of Microsoft ...

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.



我以为我明白这一点,但我刚刚在我的应用程序中遇到了异常行为,其中 TempData值(value)是可用的,它不应该是可用的。一般来说,我有一个带有一系列 Action 的 Controller ,其中第一个 Action 设置了 TempData值,接下来的几个操作读取然后设置 TempData值,最后一个 Action 读取 TempData 值。伪代码如下...

[HttpPost]
public ActionResult Step1()
{
  TempData["bar"] = foo;
  return RedirectToAction("Step2");
}

public ActionResult Step2()
{
  var foo = TempData["bar"];
  TempData["bar"] = foo;
  return View();
}

[HttpPost]
public ActionResult Step2()
{
  var foo = TempData["bar"];
  TempData["bar"] = foo;
  return RedirectToAction("Step3");
}

public ActionResult Step3()
{
  var foo = TempData["bar"];
  TempData["bar"] = foo;
  return View();
}

[HttpPost]
public ActionResult Step3()
{
  var foo = TempData["bar"];
  return RedirectToAction("AnotherAction", "AnotherController");
}

我的信念是,在读取一个值后,它在 TempData 中将不再可用。但是我开始逐步执​​行代码,虽然键/值会在分配时添加到 TempData,但当我从 TempData 中提取值时它永远不会消失(即使我到达不同的 Controller )。

我能够让它消失的唯一方法是手动点击从 TempData 读取的操作。 .

任何人都可以提供任何指示以帮助我更好地了解 TempData 的情况ASP.NET MVC 2 中的持久性?

最佳答案

我要把这个扔出去...

RedirectToAction 的返回类型为 RedirectToRouteResult。这是由上面伪代码中的几个操作方法调用的。

根据这个possibly outdated blog entry ...

4.RedirectResult and RedirectToRouteResult always calls TempData.Keep()





Calling Keep() from within an action method ensures that none of the items in TempData are removed at the end of the current request, even if they were read. The second overload can be used to retain specific items in TempData.



所以看起来我的 TempData 值正在被自动标记。我通过看到这些值显示在 TempData 中的 _initialKeys 下来验证这一点。

关于asp.net-mvc-2 - 在 ASP.NET MVC 2 中读取后仍保留 TempData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3982465/

相关文章:

asp.net - 服务层和 ASP.NET MVC 2 的用途

asp.net-mvc-3 - 为什么 TempData[] 不适用于 IE

c# - “Tempdata”在当前上下文中不存在

c# - 将数据从 Controller 传递到 View MVC 时为空 TempData

asp.net-mvc-2 - 获取与 MVC 项目关联的区域

javascript - MVC2 IIS - 在部署时正确解析外部样式表和脚本中的 URL?

asp.net-mvc - 如何在 MVC 2 的双向绑定(bind) View 中格式化日期?

asp.net-mvc-2 - 将 IIS7 更新到 .NET 4.5 时出现 ASP.NET MVC 2 站点问题

asp.net-mvc - ASP.NET MVC CookieTempDataProvider.DeserializeTempData 返回 null

ASP.NET TempData 即使在阅读后也不会被清除