ViewData 和 ViewBag 有什么区别?

发布于 2024-10-12 03:29:13 字数 82 浏览 7 评论 0原文

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

I saw the ViewBag in MVC 3. How's that different than ViewData in MVC 2?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

一场春暖 2024-10-19 03:29:13

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

所以基本上它

ViewData["Foo"]

magic 属性: 替换 magic strings: ,

ViewBag.Foo

而你没有编译时安全性。

我仍然责怪微软在 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:

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.

The name of the properties are case sensitive.

情深如许 2024-10-19 03:29:13

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

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

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

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

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

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

烟若柳尘 2024-10-19 03:29:13

所有答案都表明 ViewBag 和/或 ViewData 是将数据从 Controller 传递到 Views 这是错误的信息。两者对于将数据从视图传递到布局或部分到视图(或 ViewComponents 等)都非常有用,它不是控制器独有的。

因为默认的 asp.net 示例在布局页面

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

和任何视图中

ViewData["Title"] = "Details";

都有这个:那么,要问这个问题:“ViewBagViewData 之间有什么区别?”

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

请注意,里面的数据相同

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

何时使用其中之一?

  • ViewBag 不支持无效的 C# 名称。
    您无法使用 ViewBag 访问 ViewData["Key With Space"]
  • ViewBag.Something 是动态的,调用方法时可能会出现问题 (像扩展方法)需要在编译时知道确切的参数。
  • 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/or ViewData is to pass data from Controller to Views 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:

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

and in any view

ViewData["Title"] = "Details";

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

The most notable difference is ViewData is a Strongly Typed Dictionary while
ViewBag is a dynamic type.

Note that the data inside IS THE SAME

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

When to use one or another?

  • ViewBag doesn't support not valid C# names.
    you can't access ViewData["Key With Space"] with ViewBag
  • 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 like ContainsKey, Add, etc. so you can use ViewData.Add("somekey", "somevalue") keep in mind it might throw exceptions.
  • Using ViewData on views needs TypeCasting while ViewBag 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 of ViewData["AnyKey"]

神也荒唐 2024-10-19 03:29:13

MVC 中的 ViewBag 与 ViewData

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

ViewBag 和 ViewBag 之间的相似之处查看数据:

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

ViewBag 和 ViewBag 之间的区别查看数据:

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

ViewBag & ViewData示例:

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

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

在View中调用

@ViewBag.Name    
@ViewData["Name"]

ViewBag vs ViewData in MVC

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

Similarities between 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:

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.

ViewBag & ViewData Example:

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"]
月野兔 2024-10-19 03:29:13

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

ViewBag:它不需要对复杂数据类型进行类型转换。

考虑以下示例:

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(); 
    }
}

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>

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:

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 View is as follows:

@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>
靑春怀旧 2024-10-19 03:29:13

我可以建议您不要使用两者吗?

如果您想将数据“发送”到屏幕,请发送强类型对象(又名 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.

绝情姑娘 2024-10-19 03:29:13

有一些细微的差异,这意味着您可以通过与视图略有不同的方式使用 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.

鸠魁 2024-10-19 03:29:13

下面是关于ViewData、ViewBag、TempData 和TempData 的点对点区别。会议。
信用/复制askforprogram.in,请点击我此处未提及的代码示例链接。

  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 Framework 4.0 及更高版本。
    • ViewBag 使用属性并处理它,因此不需要进行类型转换
      枚举。
    • ViewBag 对象仅保留当前请求的数据。
  3. MVC 中的临时数据

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

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

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.

  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.
蓝海似她心 2024-10-19 03:29:13

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

孤独岁月 2024-10-19 03:29:13

尽管选择一种格式可能没有技术优势
另一个,您应该了解两者之间的一些重要区别
语法。
一个明显的区别是 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

时光是把杀猪刀 2024-10-19 03:29:13
public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}

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

In View:

@ViewBag.Name 
@ViewData["Name"] 
public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}

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

In View:

@ViewBag.Name 
@ViewData["Name"] 
拿命拼未来 2024-10-19 03:29:13

通过这种方式,我们可以让它使用这些值将控制器之间的信息传递到带有 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

叫思念不要吵 2024-10-19 03:29:13

我注意到 ViewData 和 ViewBag 之间的一个主要区别是:

ViewData :它会返回对象,无论您分配了什么,并且需要再次类型转换回原始类型。

ViewBag :它足够智能,可以返回您分配给它的确切类型,无论您分配的是简单类型(即 int、string 等)还是复杂类型。

例如:控制器代码。

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

查看代码。

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId    @item.productName</li>
            }
        </ul>

输出屏幕。

在此处输入图像描述

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.

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

View Code.

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId    @item.productName</li>
            }
        </ul>

OutPut Screen.

enter image description here

木槿暧夏七纪年 2024-10-19 03:29:13

ViewData

  1. ViewData 用于将数据从控制器传递到视图
  2. 它派生自 ViewDataDictionary 类
  3. 仅适用于当前请求
  4. 需要对复杂数据类型进行类型转换并检查 null 值以避免错误
  5. 如果发生重定向,则其值变为 null

ViewBag

  1. ViewBag 也是用于将数据从控制器传递到相应的视图
  2. ViewBag 是一个动态属性,利用了 C# 4.0 中的新动态功能
  3. 它也仅适用于当前请求
  4. 如果发生重定向,则其值变为 null
  5. 不需要类型转换对于复杂数据类型

ViewData

  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null

ViewBag

  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type
各自安好 2024-10-19 03:29:13

这里ViewDataViewBag都用于将数据从Controller传递到View

1. ViewData

-- ViewData 是从 ViewDataDictonary 类派生的字典对象。

-- 数据只允许一个请求,当页面重定向发生时,ViewData 值会被清除。

-- ViewData 值在使用前必须键入 cate。

示例:

public ActionResult PassingDatatoViewWithViewData()
{
      ViewData["Message"] = "This message shown in view with the ViewData";
      return View();
}

View 中的

@ViewData["Message"];

控制器中-- ViewData 是像 KeyValue 这样的对,Message 是 Key,单引号中的 value 是 Value。

-- 数据很简单,所以我们不能在这里使用类型转换,如果数据复杂则使用类型转换。

public ActionResult PassingDatatoViewWithViewData()
{
      var type= new List<string>
    {
        "MVC",
        "MVP",
        "MVVC"
    };
    ViewData["types"] = type;
    return View();
}

-- 在视图中数据可以提取为

<ul>
        @foreach (var items in (List<string>)ViewData["types"])
        {
         <li>@items</li>
        }
  </ul>

2。 ViewBag

--ViewBag 使用动态功能。ViewBag 围绕 ViewData 进行包装。

-- 在 ViewBag 中需要进行类型转换。

-- 与 ViewData 相同,如果发生重定向,则值变为 null。

示例:

public ActionResult PassingDatatoViewWithViewBag()
{
          ViewData.Message = "This message shown in view with the ViewBag";
          return View();
}

In View

@ViewBag.vbMessage

--对于复杂类型使用 ViewBag

public ActionResult PassingDatatoViewWithViewBag()
{
          var type= new List<string>
        {
            "MVC",
            "MVP",
            "MVVC"
        };
        ViewBag.types = type;
        return View();
 }

-- In View 数据可以提取为

<ul>
       @foreach (var items in ViewBag.types)
       {
         <li>@items</li>
       }
</ul>

-- 主要区别在于 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

public ActionResult PassingDatatoViewWithViewData()
{
      ViewData["Message"] = "This message shown in view with the ViewData";
      return View();
}

In View

@ViewData["Message"];

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

public ActionResult PassingDatatoViewWithViewData()
{
      var type= new List<string>
    {
        "MVC",
        "MVP",
        "MVVC"
    };
    ViewData["types"] = type;
    return View();
}

-- In View data can be extracted as

<ul>
        @foreach (var items in (List<string>)ViewData["types"])
        {
         <li>@items</li>
        }
  </ul>

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:

public ActionResult PassingDatatoViewWithViewBag()
{
          ViewData.Message = "This message shown in view with the ViewBag";
          return View();
}

In View

@ViewBag.vbMessage

--For Complex type use ViewBag

public ActionResult PassingDatatoViewWithViewBag()
{
          var type= new List<string>
        {
            "MVC",
            "MVP",
            "MVVC"
        };
        ViewBag.types = type;
        return View();
 }

-- In View data can be extracted as

<ul>
       @foreach (var items in ViewBag.types)
       {
         <li>@items</li>
       }
</ul>

-- the main difference is that ViewBag not required typecasting but ViewData is required typecasting.

你爱我像她 2024-10-19 03:29:13

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 中,我们可以像这样设置值:

      ViewBag.Name = "Value"; 

并且可以按如下方式访问:

          @ViewBag.Name

而在 ViewData 中,可以按如下方式设置和访问值:
设置 ViewData 如下:

ViewData["Name"] = "Value";

并访问这样的值

 @ViewData["Name"] 

有关更多详细信息 点击这里:

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 :

      ViewBag.Name = "Value"; 

and can access as follows:

          @ViewBag.Name

While in case of ViewData the values can be set and accessed as follows:
Setting ViewData as follows :

ViewData["Name"] = "Value";

and accessing value like this

 @ViewData["Name"] 

For more details click here:

好久不见√ 2024-10-19 03:29:13

ViewBag

  1. 它返回类型对象。
  2. 它是 ControllerBase 类的动态 属性。
  3. ViewBag 仅适用于 .NET Framework 4.0 及更高版本。
  4. 它在使用前不需要 TypeCasting,因为 ViewBag 属性本质上是动态
  5. ViewBag 返回动态类型对象,其属性也是动态
  6. 它比 ViewData 快一点。

ViewData

  1. 它返回键值字典对集合。
  2. ViewData 是一个字典对象,它是 ControllerBase 类的属性。
  3. ViewDataViewBag 更快。
  4. 枚举时需要类型转换代码,因为它是字典对集合。
  5. ViewData 返回对象(键值对和值的类型为object类型,所以使用前需要进行强制转换)

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

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

在View中调用

@ViewBag.Name    
@ViewData["Name"]

ViewBag

  1. It returns Type Object.
  2. It is a dynamic property of ControllerBase class.
  3. ViewBag only works with .NET Framework 4.0 and above.
  4. It does not require TypeCasting before use since ViewBag property is dynamic in nature.
  5. ViewBag returns Dynamic Type Object and its properties are also dynamic.
  6. It is bit faster than ViewData.

ViewData

  1. It returns Key-Value Dictionary pair collection.
  2. ViewData is a dictionary object and it is property of ControllerBase class.
  3. ViewData is faster than ViewBag.
  4. Type Conversion code is required while enumerating since its a Dictionary Pair Collections.
  5. ViewData returns the object (type of key-value pair and value is type object, so you need to cast before use)

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

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

Calling in View

@ViewBag.Name    
@ViewData["Name"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文