gpt4 book ai didi

c# - 为什么在 tempData 中添加很多项目时 tempData 总是 null?

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:28 26 4
gpt4 key购买 nike

为什么在 TempData 中添加很多项时 TempData 总是 null?

我在 Controller 中的代码:

TempData[Partial1.TempDataKey] = "bla bla";
TempData[Partial2.TempDataKey] = "bla bla 2";

我的布局代码:

@{Html.RenderPartial(MVC.Administrator.Shared.Views._Partial1);}
@{Html.RenderPartial(MVC.Administrator.Shared.Views._Partial2);}

我在 _Partial1 中的代码:

<span>@(TempData.ContainsKey(Partial1.TempDataKey))</span>

我在 _Partial2 中的代码:

<span>@(TempData.ContainsKey(Partial2.TempDataKey))</span>

结果总是:

<span>False</span>
<span>False</span>

当我在 Controller 中删除它们时:

TempData[Partial1.TempDataKey] = "bla bla";
//TempData[Partial2.TempDataKey] = "bla bla 2";

那么结果是:

  <span>True</span>

最佳答案

TempData 中的变量在被访问后会自动标记为删除。您可以通过显式调用 Keep 方法来保留它们

You can use a TempDataDictionary object to pass data in the same waythat you use a ViewDataDictionary object. However, the data in aTempDataDictionary object persists only from one request to the next,unless you mark one or more keys for retention by using the Keepmethod. If a key is marked for retention, the key is retained for thenext request.

A typical use for a TempDataDictionary object is to passdata from an action method when it redirects to another action method.For example, an action method might store information about an errorin the controller's TempData property (which returns aTempDataDictionary object) before it calls the RedirectToActionmethod. The next action method can then handle the error and render aview that displays an error message.

来源:TempDataDictionary Class

因为我对它的生命周期很好奇,所以如果有兴趣进一步阅读,我浏览了源代码并写了关于它的博客:Inner-workings of TempData in ASP.NET MVC 5

您还可以调用 Peek 方法来检索值并仍然保留它们。

关于c# - 为什么在 tempData 中添加很多项目时 tempData 总是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34944237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com