在ASP.NET MVC 2中读取后,TempData保持不变

时间:2010-10-20 21:29:20

标签: asp.net-mvc-2 tempdata

在ASP.NET MVC 2中,TempData值会持续到会话结束或读取为止。在words of Microsoft ...

  

TempData的值一直持续到   它被读取或直到会话时间   出。以这种方式持久化TempData   启用重定向等方案   因为TempData中的值是   超出单一要求。

我以为我理解了这一点,但我在我的应用程序中遇到了异常行为,其中TempData值可用并且它不应该可用。通常,我有一个控制器,其中包含一系列操作,其中第一个操作设置TempData值,接下来的几个操作读取然后设置TempData值,最后一个操作读取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中提取值时,它永远不会消失(即使我到达不同的控制器)

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

任何人都可以提供任何指示来帮助我更好地理解ASP.NET MVC 2中TempData持久性的变化吗?

1 个答案:

答案 0 :(得分:10)

我要把它扔出去......

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

根据possibly outdated blog entry ...

  

4.RedirectResult和RedirectToRouteResult始终调用   TempData.Keep()

  

从动作中调用Keep()   方法确保没有任何项目   在TempData的末尾删除   当前的请求,即使它们是   读。可以使用第二个过载   保留TempData中的特定项目。

因此看起来我的TempData值会被自动标记。我通过在TempData中的_initialKeys下显示这些值来验证这一点。

相关问题