How does ViewBag in ASP.NET MVC work behind the scenes?

https://stackoverflow.com/a/16950197/3782855

ViewBag is a property of ControllerBase. It is defined as follows:

public Object ViewBag { get; }

Note that this signature is actually incorrect. Here's what the source code actually looks like:

public dynamic ViewBag {
get {
if (_dynamicViewDataDictionary == null) {
_dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewDataDictionary;
}
}

_dynamicViewDataDictionary is an ExpandoObject; you can add properties to it at runtime. Its lifetime is the same as that of the controller, which is the lifetime of the HTTP request.

https://stackoverflow.com/a/16950006/3782855

ViewBag is a property of ControllerBase, which all controllers must inherit from. It's a dynamic object, that's why you can add new properties to it without getting compile time errors.

It's not static, it's a member of the object. During the request lifetime, the controller instance is created and disposed, so you won't have "concurrency" problems, like overwriting the value.

The View (and its variants) method is not static as well, and this is how the view receives the ViewBag values: during the process of rendering the view, the controller instance has its ViewBag instance as well.

MVC ViewBag Best Practice

ViewBag is a dynamic dictionary.

So when using ViewBag to transfer data between action methods and views, your compiler won't be able to catch if you make a typo in your code when trying to access the ViewBag item in your view. Your view will crash at run time :(

Generally it is a good idea to use a view model to transfer data between your action methods and views.

view model is a simple POCO class which has properties specific to the view.

So if you want to pass some additional data to view, Add a new property to your view model and use that.Strongly typed Views make the code cleaner and more easy to maintain.

With this approach, you don't need to do explicit casting of your viewbag dictionary item to some types back and forth which you have to do with view bag.

public class ProductsForCategoryVm
{
public string CategoryName { set;get; }
public List<ProductVm> Products { set;get;}
}
public class ProductVm
{
public int Id {set;get;}
public string Name { set;get;}
}

And in your action method, create an object of this view model, load the properties and send that to the view.

public ActionResult Category(int id)
{
var vm= new ProductsForCategoryVm();
vm.CategoryName = "Books";
vm.Products= new List<ProductVm> {
new ProductVm { Id=, Name="The Pragmatic Programmer" },
new ProductVm { Id=, Name="Clean Code" }
}
return View(vm);
}

And your view, which is strongly typed to the view model,

@model ProductsForCategoryVm
<h2>@Model.CategoryName</h2>
@foreach(var item in Model.Products)
{
<p>@item.Name</p>
}

Dropdown data ?

A lot of tutorials/books has code samples which uses ViewBag for dropdown data.

I personally still feel that ViewBag's should not be used for this.

It should be a property of type List<SelectListItem> in your view model to pass the dropdown data.

Here is a post with example code on how to do that.

Are there situations where a ViewBag is absolutely necessary?

There are some valid use cases where you can(not necessary) use ViewBag to send data.

For example, you want to display something on your Layout page, you can use ViewBag for that.

Another example is ViewBag.Title (for the page title) present in the default MVC template.

注意ViewBag.AnnouncementForEditors的使用,AnnouncementForEditors是直接加到dynamic类型的ViewBag上的。

public ActionResult Create()
{
ViewBag.AnnouncementForEditors="Be careful";
return View();
}

And in the layout, you can read the ViewBag.AnnouncementForEditors

因为后端代码,加了对应的属性,所以在前端代码里可以直接使用

<body>
<h1>@ViewBag.AnnouncementForEditors</h1>
<div class="container body-content">
@RenderBody()
</div>
</body>

viewbag的更多相关文章

  1. 在Asp.net MVC 3 web应用程序中,我们会用到ViewData与ViewBag,对比一下:

    Asp.net MVC中的ViewData与ViewBag ViewData ViewBag 它是Key/Value字典集合 它是dynamic类型对像 从Asp.net MVC 1 就有了 ASP. ...

  2. MVC中在RAZOR 模板里突然了现了 CANNOT RESOLVE SYMBOL ‘VIEWBAG’ 的错误提示

    然后在Razor中出现了@ViewBag的不可用,@Url不可用,@Html 这些变量都不能用了. 异常提示: 编译器错误消息: CS0426: 类型“XX.Model.System”中不存在类型名称 ...

  3. .NET Mvc中ViewBag、ViewData、TempData如何使用

    ViewBag 获取动态视图数据字典 作用:给视图传递数据,不需要转换类型,由系统动态解析,比ViewData执行性能要差 ViewData   获取或设置视图数据的字典         给视图传递数 ...

  4. Asp.net MVC的ViewData与ViewBag以及TemplateData的使用与区别

    ViewData ViewBag 它是Key/Value字典集合 它是dynamic类型对像 从Asp.net MVC 1 就有了 ASP.NET MVC3 才有 基于Asp.net 3.5 fram ...

  5. ASP.NET MVC中viewData、viewBag和templateData的使用与区别

    一:类型比较 1.1)ViewBag是动态类型(dynamic). 1.2)ViewData是一个字典型的(Dictionary)-->ViewDataDictionary. 1.3)TempD ...

  6. asp.net mvc中ViewData、ViewBag和TempData的详解

    一.ViewData和ViewBag 1.ViewData和ViewBag都是从Action向View传递数据的方式,当然还有其他方式如向View传递Model. 2.ViewData页面查询数据时需 ...

  7. 怎么在js中,访问viewbag,viewdata等等的值

    在js中要访问viewbag,viewdata存储的值, var ss='@ViewBag.name'; 一定要加引号,单双随便,还有, ViewBag一定要写规范,不然会编译错误! 成功者的秘诀就是 ...

  8. ASP.NET MVC中viewData、viewBag和templateData的区别

    在MVC3开始,视图数据可以通过ViewBag属性访问,在MVC2中则是使用ViewData.MVC3中保留了ViewData的使用.ViewBag是动态类型(dynamic),ViewData是一个 ...

  9. ViewBag是如何实现的

    ExpandoObject 在 MVC 3 的时候 Controller 可以通过 ViewBag 将数据传送到 View.如下就是通过 ViewBag 设置页面标题: public ActionRe ...

  10. MVC3之ViewData与ViewBag

    首先先用代码来说话: ViewData: public ActionResult Index() { List<string> colors = new List<string> ...

随机推荐

  1. .symtab

    参考:剖析.o文件ELF组成 目标文件 .symtab中记录的符号是从.s文件来的,所以.s这个汇编文件很关键. .symtab所记录符号的种类 示例代码 a.c ; static float a_v ...

  2. 【DevOps】在CentOS中安装DockerCE

    准备 安装好CentOS7,拥有root账号密码,使用客户端登录. 安装 启动进入root用户,复制以下代码执行即可 yum install -y yum-utils device-mapper-pe ...

  3. nginx的应用【静态代理、动静分离】

    Nginx主要应用: 静态web服务器 负载均衡 静态代理虚拟主机 静态代理 :把所有静态资源的访问改为访问nginx,而不是访问tomcat,因为nginx更擅长于静态资源的处理,性能更好,效率更高 ...

  4. k8s的网络

    K8S的网络中主要存在4种类型的通信:   ①同一Pod内的容器间通信 ②各个Pod彼此间的通信 ③Pod和Service间的通信 ④集群外部流量和Service之间的通信   K8S为Pod和Ser ...

  5. 【PAT-二叉树】L2-011. 玩转二叉树- 仅仅开100大的数组模拟即可!

    L2-011. 玩转二叉树 给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列.所谓镜面反转,是指将所有非叶结点的左右孩子对换.(我的分析:无非就是说把左子树当成 ...

  6. angular ionic 解决微信页面缓存问题

    # 在路由对应的页面路径后面加时间戳 .state('viewName', { url: '/viewName', cache: false, templateUrl: function(){ ret ...

  7. POJ1185 炮兵阵地 和 POJ2411 Mondriaan's Dream

    炮兵阵地 Language:Default 炮兵阵地 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 34008 Accepted ...

  8. Selenium常用API的使用java语言之6-WebDriver常用方法

    前面我们已经学习了定位元素, 定位只是第一步, 定位之后需要对这个元素进行操作, 或单击(按钮) 或 输入(输入框) , 下面就来认识这些最常用的方法. 1.WebDriver 常用方法 下面先来认识 ...

  9. Codeforces Round #533 (Div. 2) E. Helping Hiasat(最大独立集)

    题目链接:https://codeforces.com/contest/1105/problem/E 题意:有 n 个事件,op = 1 表示我可以修改昵称,op = 2 表示一个名为 s_i 的朋友 ...

  10. CF480E Parking Lot(two-pointers + 单调队列优化)

    题面 动态加障碍物,同时查询最大子正方形. n,m≤2000n,m\leq2000n,m≤2000 题解 加障碍不好做,直接离线后反着做,每次就是清除一个障碍物. 显然倒着做答案是递增的,而且答案的值 ...