asp.net-mvc ViewData、ViewBag、Session、TempData 的正确时间是什么时候
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12676924/
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
What is the right time for ViewData, ViewBag, Session, TempData
提问by MrM
I was editing a project and I saw a Session[""] in one controller method and TempData[""] in another. Is there a difference between the 4 or is it just 4 ways to do the same thing.
我正在编辑一个项目,我在一个控制器方法中看到了一个 Session[""],在另一个控制器方法中看到了一个 TempData[""]。这 4 种方法之间有区别吗,还是只有 4 种方法可以做同样的事情。
回答by Darin Dimitrov
- ViewData/ViewBag- valid only for the duration of the current request.
You set it in a controller action and use it in the view, then it disappears.
The difference is that the first is a dictionary whereas the second is just adynamicwrapper around this dictionary.
Both point to the same data though.
ViewBag was introduced in ASP.NET MVC 3.
- ViewData/ViewBag- 仅在当前请求期间有效。
您在控制器操作中设置它并在视图中使用它,然后它就会消失。
不同之处在于第一个是字典,而第二个只是dynamic这本字典的包装器。
两者都指向相同的数据。
ViewBag 是在 ASP.NET MVC 3 中引入的。
Example:
例子:
public ActionResult Index()
{
ViewData["foo"] = "bar";
return View();
}
and inside the view you could use this value:
在视图中,您可以使用此值:
<div>@ViewData["foo"]</div>
Same with ViewBag but it is dynamic:
与 ViewBag 相同,但它是动态的:
public ActionResult Index()
{
ViewBag.foo = "bar";
return View();
}
and inside the view you could use this value:
在视图中,您可以使用此值:
<div>@ViewBag.foo</div>
So as you can see ViewData/ViewBag are just an alternative way to pass information to a view from a controller action compared to the classic and recommended way which is using a view model:
因此,与使用视图模型的经典和推荐方式相比,ViewData/ViewBag 只是从控制器操作向视图传递信息的另一种方法:
public class MyViewModel
{
public string Foo { get; set; }
}
and then:
进而:
public ActionResult Index()
{
var model = new MyViewModel { Foo = "bar" };
return View(model);
}
and inside your strongly typed view:
在你的强类型视图中:
@model MyViewModel
<div>@Html.DisplayFor(x => x.Foo)</div>
As you can see using view models provide a strongly typed approach in passing information to a view from a controller action.
正如您所看到的,使用视图模型提供了一种强类型方法,可以将信息从控制器操作传递给视图。
- TempData- it allows for persisting information for the duration of a single subsequent request. You store something inside TempData and then redirect. In the target controller action to which you redirected you could retrieve the value that was stored inside TempData.
- TempData- 它允许在单个后续请求期间保留信息。您在 TempData 中存储一些东西,然后重定向。在您重定向到的目标控制器操作中,您可以检索存储在 TempData 中的值。
Example:
例子:
public ActionResult Foo()
{
TempData["foo"] = "bar";
return RedirectToAction("bar");
}
public ActionResult Bar()
{
var value = TempData["foo"] as string;
// use the value here. If you need to pass it to the view you could
// use ViewData/ViewBag (I can't believe I said that but I will leave it for the moment)
return View();
}
ASP.NET MVC will automatically expire the value that was stored in TempDataonce you read it. Under the covers ASP.NET MVC persists the information into the Session.
ASP.NET MVC 将在TempData您读取它后自动使存储的值过期。在幕后 ASP.NET MVC 将信息持久化到Session.
- Session- same as TempData except that it never expires - it will be valid for all requests, not a single redirect.
- 会话- 与 TempData 相同,除了它永不过期 - 它将对所有请求有效,而不是单个重定向。
回答by marvelTracker
ASP.net MVC introduced ViewData, ViewBag, TempData, Sessionto pass data between controller to view.
ASP.net MVC 引入了ViewData、ViewBag、TempData、Session来在控制器之间传递数据来查看。
ViewData
查看数据
ViewData is implemented by using ViewDataDictionaryclass which stored in CurrentRequestContext. So, ViewData life-cycle will end when the current request ends.
ViewData 是通过使用存储在CurrentRequestContext 中的ViewDataDictionary类实现的。因此,ViewData 生命周期将在当前请求结束时结束。
ViewBagis also like ViewData, and only difference is it enable dynamically sharing the data using dynamics objects.
ViewBag也和 ViewData 类似,唯一的区别是它允许使用动态对象动态共享数据。
TempDatais a very short-lived instance, and you should only use it during the currentand the subsequentrequests only.This will be handy if you want to use Redirections(RedirectToAction, RedirectToRoute, Redirect) in ASP.net MVC and pass some data among redirects. TempData stores data in Session but framework disposes the data when current and subsequent requests ends.
TempData是一个非常短暂的实例,你应该只在当前和后续请求中使用它。如果你想在 ASP.net MVC 中使用 Redirections(RedirectToAction, RedirectToRoute, Redirect) 并传递一些数据,这将很方便重定向之间。TempData 将数据存储在 Session 中,但框架在当前和后续请求结束时处理数据。
Sessionis long-lived(Never expires) data that belongs to user session.You need to be mindful when you use session variables which can be easily cause issues.
会话是属于用户会话的长期(永不过期)数据。您在使用会话变量时需要注意,这很容易导致问题。
protected void Session_Start(Object sender, EventArgs e)
{
int userType = 1;
HttpContext.Current.Session.Add("_SessionUserType",userType );
}
回答by Elnaz
ViewData:
查看数据:
- Is a special dictionary inherited from
ViewDataDictionary. - Used to send data from controller to view.
- It's life span is the current request.
- It will be destroyed if you have
Redirect. - For security reasons, it's better to check it for
nullbefore usage. - The casting should be done for the operation.
- 是从
ViewDataDictionary. - 用于从控制器发送数据以查看。
- 它的生命周期是当前的请求。
- 如果你有,它就会被摧毁
Redirect。 - 出于安全原因,最好
null在使用前检查它。 - 应为手术进行铸造。
ViewBag:
查看包:
Is a dynamic type (this type is presented in c#4).
Like
ViewDatais used to send data from the controller to the view.- The duration of the validity of its values ??in the current request.
- In redirection between pages, its value will be null.
- For security reasons before use, check it for
null. - The casting is not necessary, so it's more faster than
ViewData.
是动态类型(该类型在 c#4 中出现)。
Like
ViewData用于将数据从控制器发送到视图。- 其值在当前请求中的有效期的持续时间。
- 在页面间重定向时,其值为空。
- 出于安全原因,请在使用前检查
null. - 铸造不是必需的,所以它比
ViewData.
TempData:
临时数据:
- A special kind of dictionary derived from
TempDataDictionary. - It has Short life time, and used to send information between pages (
Redirect). - After rendering the
Viewcompletely, its value will benull. - For security reasons before use, check it for
null. - The casting should be done for the operation.
- 一种特殊的字典,源自
TempDataDictionary. - 它的生命周期很短,用于在页面之间发送信息 (
Redirect)。 View完全渲染后,其值为null。- 出于安全原因,请在使用前检查
null. - 应为手术进行铸造。
Session:
会议:
- used To send information between different requests.
- Its value is not
nullnot null values; Unless after a certain time (session expire). - For security reasons before use, check it for
null. - The casting should be done for the operation.
- 用于在不同请求之间发送信息。
- 它的值
null不是空值;除非经过一段时间(session expire)。 - 出于安全原因,请在使用前检查
null. - 应为手术进行铸造。
Thisarticle explains the difference between ViewData, ViewBag and TempData. I hope you can refer this article for your need.
这篇文章解释了 ViewData、ViewBag 和 TempData 之间的区别。我希望您可以根据需要参考这篇文章。

