.net ViewData 和 ViewBag 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4705426/
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-03 15:08:38  来源:igfitidea点击:

What's the difference between ViewData and ViewBag?

.netasp.net-mvc-3differenceviewbagviewdata

提问by user469652

I saw the ViewBagin MVC 3. How's that different than ViewDatain MVC 2?

ViewBag在 MVC 3 中看到了。它与ViewDataMVC 2 中的有什么不同?

回答by Darin Dimitrov

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).

它使用 C# 4.0 动态特性。它实现了与 viewdata 相同的目标,应该避免使用强类型视图模型(应避免使用与 viewdata 相同的方式)。

So basically it replaces magic strings:

所以基本上它取代了魔法字符串

ViewData["Foo"]

with magic properties:

具有魔法属性

ViewBag.Foo

for which you have no compile time safety.

您没有编译时安全性。

I continue to blame Microsoft for ever introducing this concept in MVC.

我继续责怪微软在 MVC 中引入了这个概念。

The name of the properties are case sensitive.

属性名称区分大小写。

回答by Rich Bianco

Internally ViewBagproperties are stored as name/value pairs in the ViewData dictionary.

ViewBag属性在内部以名称/值对的形式存储在ViewData 字典中

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:

注意:在 MVC 3 的大多数预发布版本中,ViewBag 属性被命名为 ViewModel,如 MVC 3 发行说明中的​​此代码段所述:

(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

(编辑 10-8-12)有人建议我发布我发布的此信息的来源,这是来源:http: //www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4

MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. 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 property.)

MVC 2 控制器支持 ViewData 属性,该属性使您能够使用后期绑定字典 API 将数据传递到视图模板。在 MVC 3 中,您还可以使用更简单的语法与 ViewBag 属性来实现相同的目的。例如,您可以编写 ViewBag.Message="text",而不是编写 ViewData["Message"]="text"。您不需要定义任何强类型类来使用 ViewBag 属性。因为它是一个动态属性,您可以改为只获取或设置属性,它会在运行时动态解析它们。在内部,ViewBag 属性作为名称/值对存储在 ViewData 字典中。(注意:在 MVC 3 的大多数预发布版本中,ViewBag 属性被命名为 ViewModel 属性。)

回答by Arun Prakash

ViewBag vs ViewData in MVC

MVC 中的 ViewBag 与 ViewData

http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html

http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html

Similarities between ViewBag & ViewData :

ViewBag 和 ViewData 之间的相似之处:

Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It's a communication mechanism within the server call.

当您从控制器移动到视图时,有助于维护数据。用于将数据从控制器传递到相应的视图。寿命短意味着发生重定向时值变为空。这是因为他们的目标是提供一种在控制器和视图之间进行通信的方式。它是服务器调用中的一种通信机制。

Difference between ViewBag & ViewData:

ViewBag 和 ViewData 的区别:

ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn't require typecasting for complex data type.

ViewData 是从 ViewDataDictionary 类派生的对象字典,可以使用字符串作为键访问。ViewBag 是一个动态属性,它利用了 C# 4.0 中的新动态特性。ViewData 需要对复杂数据类型进行类型转换并检查空值以避免错误。ViewBag 不需要对复杂数据类型进行类型转换。

ViewBag & ViewData Example:

ViewBag 和 ViewData 示例:

public ActionResult Index()
{   
    ViewBag.Name = "Arun Prakash";   
    return View();
}

public ActionResult Index()
{  
    ViewData["Name"] = "Arun Prakash";  
    return View();
}   

Calling in View

在视图中调用

@ViewBag.Name    
@ViewData["Name"]

回答by Naresh Ravlani

ViewData: It requires type casting for complex data types and checks for null values to avoid errors.

ViewData:它需要对复杂数据类型进行类型转换并检查空值以避免错误。

ViewBag: It doesn't require type casting for complex data types.

ViewBag:它不需要复杂数据类型的类型转换。

Consider the following example:

考虑以下示例:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var emp = new Employee
        {
            EmpID=101,
            Name = "Deepak",
            Salary = 35000,
            Address = "Delhi"
        };

        ViewData["emp"] = emp;
        ViewBag.Employee = emp;

        return View(); 
    }
}

And the code for Viewis as follows:

代码View如下:

@model MyProject.Models.EmpModel;
@{ 
 Layout = "~/Views/Shared/_Layout.cshtml"; 
 ViewBag.Title = "Welcome to Home Page";
 var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}

<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.Employee.Name</h4>
<h3>@viewDataEmployee.Name</h3>

回答by Bart Calixto

All answers suggest that ViewBagand/or ViewDatais to pass data from Controllerto Viewswhich 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.

所有的答案表明,ViewBag和/或ViewData为传递数据从ControllerViews这是误传。两者对于将数据从 Views 传递到 Layout 或 Partial 到 Views(或 ViewComponents 等)都非常有用。它不是控制器独有的。

as the default asp.net sample have this in the layout page:

作为默认的 asp.net 示例在布局页面中有这个:

<title>@ViewData["Title"] - MyApp</title>

and in any view

并且在任何情况下

ViewData["Title"] = "Details";

So then, to asking the question: "what's the difference between ViewBagand ViewData?"

那么,要问这个问题:“ViewBag和之间有什么区别ViewData

The most notable difference is ViewDatais a Strongly Typed Dictionary while ViewBagis a dynamic type.

最显着的区别是ViewData强类型字典 ViewBag而是动态类型。

Note that the data inside IS THE SAME

注意里面的数据是一样的

ViewData["Title"] = "MyTitle";
ViewBag.Title; // returns "MyTitle";

When to use one or another?

何时使用一种或另一种?

  • ViewBagdoesn't support not valid C# names. you can't access ViewData["Key With Space"]with ViewBag
  • ViewBag.Somethingis dynamic and you may have problems when calling methods (like extension methods) that needs to know the exact parameter at compile time.
  • ViewBagcan check for nulls syntactical cleaner: ViewBag.Person?.Name
  • ViewDatahave all the properties of a Dictionary like ContainsKey, Add, etc. so you can use ViewData.Add("somekey", "somevalue")keep in mind it might throw exceptions.
  • Using ViewDataon views needs TypeCasting while ViewBagdon't.
  • ViewBag不支持无效的 C# 名称。你不能访问ViewData["Key With Space"]ViewBag
  • ViewBag.Something是动态的,在调用需要在编译时知道确切参数的方法(如扩展方法)时可能会遇到问题。
  • ViewBag可以检查空值语法清理器: ViewBag.Person?.Name
  • ViewData具有字典的所有属性,如ContainsKeyAdd等,因此您可以使用ViewData.Add("somekey", "somevalue")它,请记住它可能会引发异常。
  • ViewData在视图上使用需要 TypeCasting 而不需要ViewBag

Knowing the subtle differences, using one or another is much more a taste preference.

了解细微的差异,使用一个或另一个更像是一种口味偏好。

Normally you can think of ViewBag.AnyKeyto an alias of ViewData["AnyKey"]

通常你可以想到ViewBag.AnyKey一个别名ViewData["AnyKey"]

回答by nootn

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.

如果您想将数据“发送”到您的屏幕,请发送一个强类型对象(AKA ViewModel),因为它更易于测试。

If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.

如果您绑定到某种“模型”并具有随机的“viewbag”或“viewdata”项,那么它会使自动化测试变得非常困难。

If you are using these consider how you might be able to restructure and just use ViewModels.

如果您正在使用这些,请考虑如何重组并仅使用 ViewModel。

回答by Alan Macdonald

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.aspxand shows that casting can be avoided in the example by using the ViewBag instead of ViewData.

有一些细微的差异意味着您可以以与视图略有不同的方式使用 ViewData 和 ViewBag。这篇文章概述了一个优点http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx并表明铸造在示例中可以通过使用 ViewBag 而不是 ViewData 来避免。

回答by Ahmed Elbatt

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 ...

viewdata:是用于在 View 和 controller 之间存储数据的字典,您需要将视图数据对象转换为视图中的相应模型才能从中检索数据...

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:是一个动态属性,其工作方式与视图数据类似,但是它更好,因为在视图中使用它之前不需要将其转换为相应的模型......

回答by Nirju

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、ViewBag、TempData 和 Session 的点对点差异。 信用/复制 askforprogram.in,按照我在这里没有提到的代码示例的链接。

  1. ViewData in MVC

    • ViewData is property of ControllerBase class.
    • ViewData is a type of dictionary object.
    • ViewData is key-value dictionary collection.
    • ViewData was introduced in MVC 1.0 version.
    • ViewData works with .Net framework 3.5 and above.
    • Need to do type conversion of code while enumerating.
    • ViewData object keeps data only for current request.
  2. ViewBag in MVC

    • ViewBag is property of ControllerBase class.
    • ViewBag is a type of dynamic object.
    • ViewBag is a type of object.
    • ViewBag was introduced in MVC 3.0 version.
    • ViewBag works with .Net framework 4.0 and above.
    • ViewBag uses property and handles it, so no need to do type conversion while enumerating.
    • ViewBag object keeps data only for current request.
  3. TempData in MVC

    • TempData is property of ControllerBase class.
    • TempData is a type of dictionary object.
    • TempData is key-value dictionary collection.
    • TempData was introduced in MVC 1.0 version.
    • TempData works with .Net framework 3.5 and above.
    • Need to do type conversion of code while enumerating.
    • TempData object is used to data between current request and subsequent request.
  4. Session in MVC

    • Session is property of Controller(Abstract Class).
    • Session is a type of HttpSessionStateBase.
    • Session is key-value dictionary collection.
    • Session was introduced in MVC 1.0 version.
    • TempData works with .Net framework 1.0 and above.
    • Need to do type conversion of code while enumerating.
    • Session object keeps data for all requests. Valid for all requests, never expires.
  1. MVC 中的视图数据

    • ViewData 是 ControllerBase 类的属性。
    • ViewData 是一种字典对象。
    • ViewData 是键值字典集合。
    • ViewData 是在 MVC 1.0 版本中引入的。
    • ViewData 适用于 .Net framework 3.5 及更高版本。
    • 枚举时需要对代码进行类型转换。
    • ViewData 对象仅保留当前请求的数据。
  2. MVC 中的 ViewBag

    • ViewBag 是 ControllerBase 类的属性。
    • ViewBag 是一种动态对象。
    • ViewBag 是一种对象。
    • ViewBag 是在 MVC 3.0 版本中引入的。
    • ViewBag 适用于 .Net 框架 4.0 及更高版本。
    • ViewBag 使用属性并处理它,因此无需在枚举时进行类型转换。
    • ViewBag 对象仅保留当前请求的数据。
  3. MVC 中的临时数据

    • TempData 是 ControllerBase 类的属性。
    • TempData 是一种字典对象。
    • TempData 是键值字典集合。
    • TempData 是在 MVC 1.0 版本中引入的。
    • TempData 适用于 .Net framework 3.5 及更高版本。
    • 枚举时需要对代码进行类型转换。
    • TempData 对象用于当前请求和后续请求之间的数据。
  4. MVC 中的会话

    • 会话是控制器(抽象类)的属性。
    • Session 是 HttpSessionStateBase 的一种。
    • Session 是键值字典集合。
    • 会话是在 MVC 1.0 版本中引入的。
    • TempData 适用于 .Net framework 1.0 及更高版本。
    • 枚举时需要对代码进行类型转换。
    • 会话对象保存所有请求的数据。对所有请求有效,永不过期。

回答by user2211290

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

尽管选择一种格式而不是另一种格式可能没有技术优势,但您应该了解两种语法之间的一些重要差异。一个明显的区别是 ViewBag 仅在您访问的密钥是有效的 C# 标识符时才起作用。例如,如果您在 ViewData["Key With Spaces"] 中放置一个值,则无法使用 ViewBag 访问该值,因为代码将无法编译。要考虑的另一个关键问题是您不能将动态值作为参数传递给扩展方法。C# 编译器必须在编译时知道每个参数的真实类型,以便选择正确的扩展方法。如果任何参数是动态的,编译将失败。例如,此代码将始终失败:@Html.TextBox("name", ViewBag.Name)。要解决此问题,请使用 ViewData["