ViewData 和 ViewBag 有什么区别?
我在 MVC 3 中看到了 ViewBag
。它与 MVC 2 中的 ViewData
有什么不同?
I saw the ViewBag
in MVC 3. How's that different than ViewData
in MVC 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
它使用 C# 4.0 动态功能。它实现了与 viewdata 相同的目标,应该避免使用强类型视图模型(与应避免使用 viewdata 的方式相同)。
所以基本上它
用 magic 属性: 替换 magic strings: ,
而你没有编译时安全性。
我仍然责怪微软在 MVC 中引入了这个概念。
属性的名称区分大小写。
It uses the C# 4.0 dynamic feature. It achieves the same goal as viewdata and should be avoided in favor of using strongly typed view models (the same way as viewdata should be avoided).
So basically it replaces magic strings:
with magic properties:
for which you have no compile time safety.
I continue to blame Microsoft for ever introducing this concept in MVC.
The name of the properties are case sensitive.
内部ViewBag属性以名称/值对的形式存储在ViewData字典中。
注意:在 MVC 3 的大多数预发行版本中,ViewBag 属性被命名为 ViewModel,如 MVC 3 发行说明中的此代码段所述:
(于 10-8-12 编辑) 建议我发布我发布的此信息的来源,这是来源:
http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:
(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source:
http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4
所有答案都表明
ViewBag
和/或ViewData
是将数据从Controller
传递到Views
这是错误的信息。两者对于将数据从视图传递到布局或部分到视图(或 ViewComponents 等)都非常有用,它不是控制器独有的。因为默认的 asp.net 示例在布局页面
和任何视图中
都有这个:那么,要问这个问题:“
ViewBag
和ViewData
之间有什么区别?”最显着的区别是 ViewData 是强类型字典,而
ViewBag
是一种动态类型。请注意,里面的数据相同
何时使用其中之一?
ViewBag
不支持无效的 C# 名称。您无法使用
ViewBag
访问ViewData["Key With Space"]
ViewBag
可以检查 null 语法清理器:ViewBag.Person?.Name
ViewData
具有字典的所有属性,如ContainsKey、
Add
等,以便您可以使用ViewData.Add("somekey", "somevalue")
请记住,它可能会引发异常。ViewData
需要 TypeCasting,而ViewBag
则不需要。了解了细微的差异,使用其中一种或另一种更多的是一种口味偏好。
通常您可以将
ViewBag.AnyKey
视为ViewData["AnyKey"]
的别名All answers suggest that
ViewBag
and/orViewData
is to pass data fromController
toViews
which is misinformation. both are very useful to pass data from Views to Layout or Partial to Views (or ViewComponents, etc) It's not controller exclusive.as the default asp.net sample have this in the layout page:
and in any view
So then, to asking the question: "what's the difference between
ViewBag
andViewData
?"The most notable difference is
ViewData
is a Strongly Typed Dictionary whileViewBag
is a dynamic type.Note that the data inside IS THE SAME
When to use one or another?
ViewBag
doesn't support not valid C# names.you can't access
ViewData["Key With Space"]
withViewBag
ViewBag.Something
is dynamic and you may have problems when calling methods (like extension methods) that needs to know the exact parameter at compile time.ViewBag
can check for nulls syntactical cleaner:ViewBag.Person?.Name
ViewData
have all the properties of a Dictionary likeContainsKey
,Add
, etc. so you can useViewData.Add("somekey", "somevalue")
keep in mind it might throw exceptions.ViewData
on views needs TypeCasting whileViewBag
don't.Knowing the subtle differences, using one or another is much more a taste preference.
Normally you can think of
ViewBag.AnyKey
to an alias ofViewData["AnyKey"]
MVC 中的 ViewBag 与 ViewData
http ://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
ViewBag 和 ViewBag 之间的相似之处查看数据:
ViewBag 和 ViewBag 之间的区别查看数据:
ViewBag & ViewData示例:
在View中调用
ViewBag vs ViewData in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
Similarities between ViewBag & ViewData :
Difference between ViewBag & ViewData:
ViewBag & ViewData Example:
Calling in View
ViewData
:它需要对复杂数据类型进行类型转换并检查空值以避免错误。ViewBag
:它不需要对复杂数据类型进行类型转换。考虑以下示例:
View
的代码如下:ViewData
: It requires type casting for complex data types and checks for null values to avoid errors.ViewBag
: It doesn’t require type casting for complex data types.Consider the following example:
And the code for
View
is as follows:我可以建议您不要使用两者吗?
如果您想将数据“发送”到屏幕,请发送强类型对象(又名 ViewModel),因为它更容易测试。
如果您绑定到某种“模型”并具有随机的“viewbag”或“viewdata”项目,那么它会使自动化测试变得非常困难。
如果您正在使用这些,请考虑如何重组并仅使用 ViewModel。
Can I recommend to you to not use either?
If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.
If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.
If you are using these consider how you might be able to restructure and just use ViewModels.
有一些细微的差异,这意味着您可以通过与视图略有不同的方式使用 ViewData 和 ViewBag。这篇文章 http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx 并表明在示例中可以通过使用 ViewBag 而不是 ViewData 来避免强制转换。
There are some subtle differences that mean you can use ViewData and ViewBag in slightly different ways from the view. One advantage is outlined in this post http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx and shows that casting can be avoided in the example by using the ViewBag instead of ViewData.
下面是关于ViewData、ViewBag、TempData 和TempData 的点对点区别。会议。
信用/复制askforprogram.in,请点击我此处未提及的代码示例链接。
在MVC中查看数据
MVC 中的 ViewBag
枚举。
MVC 中的临时数据
MVC 中的会话
Below is the point to point difference about ViewData, ViewBag, TempData & Session.
Credit/copied askforprogram.in , Follow the link for code example that i haven't mentioned here.
ViewData in MVC
ViewBag in MVC
enumerating.
TempData in MVC
Session in MVC
viewdata:是一个字典,用于在视图和控制器之间存储数据,您需要将视图数据对象转换为视图中相应的模型,以便能够从中检索数据...
ViewBag:是一个动态属性,其工作方式与视图数据类似,但它更好,因为在视图中使用它之前不需要将其转换为相应的模型......
viewdata: is a dictionary used to store data between View and controller , u need to cast the view data object to its corresponding model in the view to be able to retrieve data from it ...
ViewBag: is a dynamic property similar in its working to the view data, However it is better cuz it doesn't need to be casted to its corressponding model before using it in the view ...
尽管选择一种格式可能没有技术优势
另一个,您应该了解两者之间的一些重要区别
语法。
一个明显的区别是 ViewBag 仅在您访问密钥时才起作用
是一个有效的 C# 标识符。例如,如果您在 ViewData["Key
使用 Spaces"],您无法使用 ViewBag 访问该值,因为代码
不会编译。
另一个需要考虑的关键问题是不能将动态值作为参数传递
到扩展方法。 C# 编译器必须知道每个的真实类型
编译时参数以便选择正确的扩展方法。
如果任何参数是动态的,编译将失败。例如,这段代码将
总是失败:@Html.TextBox("name", ViewBag.Name)。要解决这个问题,要么
使用 ViewData["Name"] 或投射 va
Although you might not have a technical advantage to choosing one format over
the other, you should be aware of some important differences between the two
syntaxes.
One obvious difference is that ViewBag works only when the key you’re accessing
is a valid C# identifi er. For example, if you place a value in ViewData["Key
With Spaces"], you can’t access that value using ViewBag because the code
won’t compile.
Another key issue to consider is that you cannot pass in dynamic values as parameters
to extension methods. The C# compiler must know the real type of every
parameter at compile time in order to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will
always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either
use ViewData["Name"] or cast the va
通过这种方式,我们可以让它使用这些值将控制器之间的信息传递到带有 TEMP DATA 的其他页面
In this way we can make it use the values to the pass the information between the controller to other page with TEMP DATA
我注意到 ViewData 和 ViewBag 之间的一个主要区别是:
ViewData :它会返回对象,无论您分配了什么,并且需要再次类型转换回原始类型。
ViewBag :它足够智能,可以返回您分配给它的确切类型,无论您分配的是简单类型(即 int、string 等)还是复杂类型。
例如:控制器代码。
查看代码。
输出屏幕。
One main difference I noticed between ViewData and ViewBag is:
ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.
ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.
Ex: Controller code.
View Code.
OutPut Screen.
ViewData
ViewBag
ViewData
ViewBag
这里ViewData和ViewBag都用于将数据从Controller传递到View。
1. ViewData
-- ViewData 是从 ViewDataDictonary 类派生的字典对象。
-- 数据只允许一个请求,当页面重定向发生时,ViewData 值会被清除。
-- ViewData 值在使用前必须键入 cate。
示例:在
View 中的
控制器中-- ViewData 是像 Key 和 Value 这样的对,Message 是 Key,单引号中的 value 是 Value。
-- 数据很简单,所以我们不能在这里使用类型转换,如果数据复杂则使用类型转换。
-- 在视图中数据可以提取为
2。 ViewBag
--ViewBag 使用动态功能。ViewBag 围绕 ViewData 进行包装。
-- 在 ViewBag 中需要进行类型转换。
-- 与 ViewData 相同,如果发生重定向,则值变为 null。
示例:
In View
--对于复杂类型使用 ViewBag
-- In View 数据可以提取为
-- 主要区别在于 ViewBag 不需要类型转换,但 ViewData 需要进行类型转换。
Here ViewData and ViewBag both are used pass data from Controller to View.
1. ViewData
-- ViewData is dictionary object that is derived from ViewDataDictonary class.
-- Data only allow for one request, ViewData values get cleared when page redirecting occurs.
-- ViewData value must be typed cate before use.
Example: In Controller
In View
-- With ViewData is a pair like Key and Value, Message is Key and in inverted comma value is Value.
-- Data is simple so we can not use typecasting here if data is complex then using type casting.
-- In View data can be extracted as
2. ViewBag
--ViewBag uses the dynamic feature.ViewBag wrapper around the ViewData.
-- In ViewBag type casting is required.
-- Same as ViewData, if redirection occurs value becomes null.
Example:
In View
--For Complex type use ViewBag
-- In View data can be extracted as
-- the main difference is that ViewBag not required typecasting but ViewData is required typecasting.
ViewBag 和 ViewData 是 ASP.Net MVC 中用于将信息从控制器传递到视图的两种方法。使用这两种机制的目标是提供控制器和视图之间的通信。两者的生命周期都很短,一旦发生重定向,即一旦页面从源页面(我们设置 ViewBag 或 ViewData 的值)重定向到目标页面,ViewBag 和 ViewData 的值都会变为 null变为空。
尽管有这些相似之处,但如果我们谈论两者的实现,则两者(ViewBag 和 ViewData)是两个不同的东西。差异如下:
1.) 如果我们明智地分析这两种实现,那么我们会发现 ViewData 是一个字典数据结构 - 派生自 ViewDataDictionary 的对象字典,并且可以使用字符串作为这些值的键进行访问,而 ViewBag 使用动态功能C#4.0 中引入,是一个动态属性。
2.) 在访问 ViewData 中的值时,我们需要对这些值(数据类型)进行类型转换,因为它们作为对象存储在 ViewData 字典中,但如果我们在 ViewBag 的情况下访问该值,则不需要这样的需要。
3.) 在 ViewBag 中,我们可以像这样设置值:
并且可以按如下方式访问:
而在 ViewData 中,可以按如下方式设置和访问值:
设置 ViewData 如下:
并访问这样的值
有关更多详细信息 点击这里:
ViewBag and ViewData are two means which are used to pass information from controller to view in ASP.Net MVC. The goal of using both mechanism is to provide the communicaton between controller and View. Both have short life that is the value of both becomes null once the redirection has occured ie, once the page has redirected from the source page (where we set the value of ViewBag or ViewData) to the target page , both ViewBag as well as ViewData becomes null.
Despite having these similarities both (ViewBag and ViewData) are two different things if we talk about the implementation of both. The differences are as follows :
1.) If we analyse both implementation wise then we will find that ViewData is a dictionary data structure - Dictionary of Objects derived from ViewDataDictionary and accessible using strings as Keys to these values while ViewBag makes use of the dynamic features introduced in C#4.0 and is a dynamic property.
2.) While accessing the values form ViewData , we need to typecast the values (datatypes) as they are stored as Objects in the ViewData dictionary but there is no such need if we are accessing th value in case of ViewBag.
3.) In ViewBag we can set the value like this :
and can access as follows:
While in case of ViewData the values can be set and accessed as follows:
Setting ViewData as follows :
and accessing value like this
For more details click here:
ViewBag
ControllerBase
类的动态
属性。ViewBag
仅适用于 .NET Framework 4.0 及更高版本。ViewBag
属性本质上是动态
。ViewBag
返回动态类型对象,其属性也是动态
。ViewData
ViewData
是一个字典对象,它是ControllerBase
类的属性。ViewData
比ViewBag
更快。ViewData
返回对象(键值对和值的类型为object类型,所以使用前需要进行强制转换)在View中调用
ViewBag
dynamic
property ofControllerBase
class.ViewBag
only works with .NET Framework 4.0 and above.ViewBag
property isdynamic
in nature.ViewBag
returns Dynamic Type Object and its properties are alsodynamic
.ViewData
.ViewData
ViewData
is a dictionary object and it is property ofControllerBase
class.ViewData
is faster thanViewBag
.ViewData
returns the object (type of key-value pair and value is type object, so you need to cast before use)Calling in View