我是MVC的新手。我想知道当我应该使用ViewData,ViewBag和TempData来传递对象时,ViewData和ViewBag的性能有什么不同吗?
答案 0 :(得分:0)
<强>的ViewData 强>
ViewData is used to pass data from controller to view
It is derived from ViewDataDictionary class
It is available for the current request only
Requires typecasting for complex data type and checks for null values to avoid error
If redirection occurs, then its value becomes null
<强> ViewBag 强>
ViewBag is also used to pass data from the controller to the respective view
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
It is also available for the current request only
If redirection occurs, then its value becomes null
Doesn’t require typecasting for complex data type
<强> TempData的强>
TempData is derived from TempDataDictionary class
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages
请参阅以下链接进行性能检查
http://spiritofdev.blogspot.in/2011/12/performance-of-c-40-dynamic-vs.html
答案 1 :(得分:0)
查看数据: View Data是一个从View Data Dictionary类派生的字典对象。 View Data是Controller Base类的属性。 视图数据用于将数据从控制器传递到相应的视图。 用法:
公共ActionResult索引()
{
ViewData.Name = "Tony Boss";
return View();
}
查看包 View Bag是一个动态属性,它利用了C#4.0中的新动态功能。 基本上它是View Data的包装器,也用于将数据从控制器传递到相应的视图。 View Bag是Controller Base类的属性。
用法:
公共ActionResult索引()
{
ViewBag.Name = "Tony Boss";
return View();
}
临时数据: Temp Data是一个字典对象,它从Temp Data Dictionary类派生并存储在短生命会话中 Temp Data是Controller Base类的属性。 Temp Data用于将数据从当前请求传递到后续请求(意味着从一个页面重定向到另一个页面)。