asp.net-mvc ViewData 和 TempData 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/173159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 22:46:21  来源:igfitidea点击:

Difference Between ViewData and TempData?

asp.net-mvc

提问by Elijah Manor

I know what ViewData is and use it all the time, but in ASP.NET Preview 5 they introduced something new called TempData.

我知道 ViewData 是什么并且一直在使用它,但是在 ASP.NET Preview 5 中,他们引入了一个叫做 TempData 的新东西。

I normally strongly type my ViewData, instead of using the dictionary of objects approach.

我通常强烈键入我的 ViewData,而不是使用对象字典的方法。

So, when should I use TempData instead of ViewData?

那么,我什么时候应该使用 TempData 而不是 ViewData?

Are there any best practices for this?

是否有任何最佳做法?

采纳答案by Dragan Panjkov

In one sentence: TempDataare like ViewData with one difference: They only contain data between two successive requests, after that they are destroyed. You can use TempDatato pass error messages or something similar.

一句话:TempData就像 ViewData 有一个区别:它们只包含两个连续请求之间的数据,之后它们被销毁。你可以TempData用来传递错误信息或类似的东西。

Although outdated, this articlehas good description of the TempDatalifecycle.

虽然已经过时,但这篇文章TempData生命周期有很好的描述。

As Ben Scheirman said here:

正如 Ben Scheirman在这里所说:

TempData is a session-backed temporary storage dictionary that is available for one single request. It's great to pass messages between controllers.

TempData 是一个会话支持的临时存储字典,可用于单个请求。在控制器之间传递消息非常棒。

回答by Captain Sensible

When an action returns a RedirectToAction result it causes an HTTP redirect (equivalent to Response.Redirect). Data can be preserved in the TempData property (dictionary) of the controller for the duration of a single HTTP redirect request.

当操作返回 RedirectToAction 结果时,它会导致 HTTP 重定向(相当于 Response.Redirect)。在单个 HTTP 重定向请求期间,数据可以保存在控制器的 TempData 属性(字典)中。

回答by Ali Adravi

ViewData:

查看数据:

  • ViewDatais a dictionary type public ViewDataDictionary ViewData { get; set; }
  • It can be used to pass data from controller to view, one way only
  • It's life lies only during the current request
  • If passing string then no need to typecast
  • If passing object then you need to typecast it but before that you need to check if it is not null
  • Its a property on ControllerBase, which is the parent of Controllerclass
  • ViewData是字典类型 public ViewDataDictionary ViewData { get; set; }
  • 它可用于将数据从控制器传递到视图,仅一种方式
  • 它的生命只在当前请求期间
  • 如果传递字符串则不需要类型转换
  • 如果传递对象,那么您需要对其进行类型转换,但在此之前您需要检查它是否不为空
  • 它是一个属性 on ControllerBase,它是Controller类的父级

TempData:

临时数据:

  1. TempDatainternally use TempDataDictionary: public TempDataDictionary TempData { get; set; }
  2. Once data is saved into TempDataDictionaryobject:
    • It persists in it and can be read from any view or any action in any controller
    • It can only be read once; once read, it becomes null
    • It is saved into session so on expiration of session data is lost.
  1. TempData内部使用TempDataDictionarypublic TempDataDictionary TempData { get; set; }
  2. 将数据保存到TempDataDictionary对象后:
    • 它保留在其中,可以从任何视图或任何控制器中的任何操作读取
    • 只能读取一次;一旦读取,它就变为空
    • 它被保存到会话中,因此会话数据到期时会丢失。

This behavior is new from ASP.NET MVC 2 and latter versions. In earlier versions of ASP.NET MVC, the values in TempDatawere available only until the next request.

此行为是 ASP.NET MVC 2 和更高版本的新行为。在 ASP.NET MVC 的早期版本中, 中的值TempData仅在下一个请求之前可用。

  1. It's alive, until it is read or session expires and can be read from anywhere.
  1. 它是活着的,直到它被读取或会话过期并且可以从任何地方读取。

See the comparison of ViewData, ViewBag, TempData and Session in MVC in detail

MVC中ViewData、ViewBag、TempData和Session的比较详解

回答by testpattern

I found this comparison useful: http://www.dotnet-tricks.com/Tutorial/mvc/9KHW190712-ViewData-vs-ViewBag-vs-TempData-vs-Session.html

我发现这个比较很有用:http: //www.dotnet-tricks.com/Tutorial/mvc/9KHW190712-ViewData-vs-ViewBag-vs-TempData-vs-Session.html

One gotcha I came across is that TempData values are cleared after they are read by default. There are options, see methods 'Peek' and 'Keep' on Msdn for more info.

我遇到的一个问题是 TempData 值在默认情况下被读取后被清除。有一些选项,请参阅 Msdn 上的“Peek”和“Keep”方法以获取更多信息

回答by Hitanshi Mehta

view data is used when we want to pass data from controller to corresponding view. view data have very short life it means it will destroy when redirection occurs. Example(Controller):

当我们想要将数据从控制器传递到相应的视图时使用视图数据。视图数据的生命周期很短,这意味着它会在发生重定向时销毁。示例(控制器):

public ViewResult try1()
    {
        ViewData["DateTime"] = DateTime.Now;
        ViewData["Name"] = "Mehta Hitanshi";
        ViewData["Twitter"] = "@hitanshi";
        ViewData["City"] = "surat";
        return View();
    }

try1.cshtm

尝试1.cshtm

<table>
<tr>
    <th>Name</th>
    <th>Twitter</th>
    <th>Email</th>
    <th>City</th>
    <th>Mobile</th>
</tr>
<tr>
    <td>@ViewData["Name"]</td>
    <td>@ViewData["Twitter"]</td>
    <td>@ViewData["City"]</td>
</tr>
</table> 

TempData transfers the data between controllers or between actions. It is used to store one time messages and its life is very short.we can use TempData.Keep() to make it available through all actions or to make it persistent.

TempData 在控制器或动作之间传输数据。它用于存储一次性消息,其生命周期很短。我们可以使用 TempData.Keep() 使其在所有操作中可用或使其持久化。

Example(Controller):

示例(控制器):

public ActionResult try3()
    {
        TempData["DateTime"] = DateTime.Now;
        TempData["Name"] = "Ravina";
        TempData["Twitter"] = "@silentRavina";
        TempData["Email"] = "[email protected]";
        TempData["City"] = "India";
        TempData["MobNo"] = 9998975436;
        return RedirectToAction("TempView1");
    }
    public ActionResult TempView1()
    {
        return View();
    }

TempView1.cshtm

TempView1.cshtm

<table>
<tr>
    <th>Name</th>
    <th>Twitter</th>
    <th>Email</th>
    <th>City</th>
    <th>Mobile</th>
</tr>
<tr>
    <td>@TempData["Name"]</td>
    <td>@TempData["Twitter"]</td>
    <td>@TempData["Email"]</td>
    <td>@TempData["City"]</td>
    <td>@TempData["MobNo"]</td>
</tr>
</table>

回答by nvirth

Just a side note to TempData.
Data in it is stored not stored until the next request, but until the next read operationis called!
See:
TempData won't destroy after second request

只是 TempData 的一个旁注。
其中的数据存储直到下一个请求才存储,而是直到下一个读取操作被调用!
请参阅:
第二次请求后 TempData 不会销毁