viewbag
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的更多相关文章
- 在Asp.net MVC 3 web应用程序中,我们会用到ViewData与ViewBag,对比一下:
Asp.net MVC中的ViewData与ViewBag ViewData ViewBag 它是Key/Value字典集合 它是dynamic类型对像 从Asp.net MVC 1 就有了 ASP. ...
- MVC中在RAZOR 模板里突然了现了 CANNOT RESOLVE SYMBOL ‘VIEWBAG’ 的错误提示
然后在Razor中出现了@ViewBag的不可用,@Url不可用,@Html 这些变量都不能用了. 异常提示: 编译器错误消息: CS0426: 类型“XX.Model.System”中不存在类型名称 ...
- .NET Mvc中ViewBag、ViewData、TempData如何使用
ViewBag 获取动态视图数据字典 作用:给视图传递数据,不需要转换类型,由系统动态解析,比ViewData执行性能要差 ViewData 获取或设置视图数据的字典 给视图传递数 ...
- Asp.net MVC的ViewData与ViewBag以及TemplateData的使用与区别
ViewData ViewBag 它是Key/Value字典集合 它是dynamic类型对像 从Asp.net MVC 1 就有了 ASP.NET MVC3 才有 基于Asp.net 3.5 fram ...
- ASP.NET MVC中viewData、viewBag和templateData的使用与区别
一:类型比较 1.1)ViewBag是动态类型(dynamic). 1.2)ViewData是一个字典型的(Dictionary)-->ViewDataDictionary. 1.3)TempD ...
- asp.net mvc中ViewData、ViewBag和TempData的详解
一.ViewData和ViewBag 1.ViewData和ViewBag都是从Action向View传递数据的方式,当然还有其他方式如向View传递Model. 2.ViewData页面查询数据时需 ...
- 怎么在js中,访问viewbag,viewdata等等的值
在js中要访问viewbag,viewdata存储的值, var ss='@ViewBag.name'; 一定要加引号,单双随便,还有, ViewBag一定要写规范,不然会编译错误! 成功者的秘诀就是 ...
- ASP.NET MVC中viewData、viewBag和templateData的区别
在MVC3开始,视图数据可以通过ViewBag属性访问,在MVC2中则是使用ViewData.MVC3中保留了ViewData的使用.ViewBag是动态类型(dynamic),ViewData是一个 ...
- ViewBag是如何实现的
ExpandoObject 在 MVC 3 的时候 Controller 可以通过 ViewBag 将数据传送到 View.如下就是通过 ViewBag 设置页面标题: public ActionRe ...
- MVC3之ViewData与ViewBag
首先先用代码来说话: ViewData: public ActionResult Index() { List<string> colors = new List<string> ...
随机推荐
- Vue-resoure 实现get post jsonp请求
1.之前学习中,如何发起数据请求? 2.常见的数据请求类型?get post jsonp 3.常见的URL请求资源地址 get请求地址: http://vue.studyit.io/api/getl ...
- Python 一些内置函数的总结~~~~
1. type() 两种用法 a. 当传入参数为一个时,返回值为参数的类型 b. 当传入参数为三个时,type(name, bases, dict) name: 类名 bases: 继承父类的元组,可 ...
- git命令——git log
功能 在提交了若干更新,又或者克隆了某个项目之后,你也许想回顾下提交历史. 完成这个任务最简单而又有效的方法是 使用git log 命令. 参数 不带任何参数 $ git log commit ca8 ...
- Win10安装MySQL5.7版本 解压缩版方法
1.下载地址:https://dev.mysql.com/downloads/mysql/5.7.html#downloads 直接点击下载项 下载后: 2.可以把解压的内容随便放到一个目录,我的是如 ...
- ubuntu安装anaconda3+tensorflow(cpu)+pycharm(windows几乎一样)
网上乱七八糟有的都是别人怎么写自己也怎么写,其实很简单. 首先是anaconda3的安装: 直接上官网:https://www.anaconda.com/download/ 下载下来之后进入文件所在目 ...
- [转]神奇的 SQL 之层级 → 为什么 GROUP BY 之后不能直接引用原表中的列
原文:https://www.cnblogs.com/youzhibing/p/11516154.html 这篇文章,对group by的讲解不错 -------------------------- ...
- 【原创】改进的大马webshell,过市面上任何防护
因为之前使用的webshell大马很多都没用了,都被安全防护拦截了,所以通过几个大牛的指点和网上的教程整理而成自己做的增强版的webshell大马,我这个是源码,部分无加密! <?php $pa ...
- 数据库概念 MySQL语法
数据库概念 将保存的数据部分,存到一个公共的地方,所有的用户涉及到数据相关都必须来这个公共地方查找 MySQL 本质就是一款基于网络通信的应用软件,任何基于网络通信的软件底层都是socket 可以把M ...
- [SCSS] SASS dynamic class properties
@mixin generateModifers($property) { #{$property}: $padding; &-large { #{$property}: $padding-la ...
- 如何在没有代理的情况下编译 tidb server
这里主要介绍 tidb server 的编译, ti kv 和 ti pd 的编译不在本文范围内: go 语言 1.11 版本之后支持 go.mod, 依赖包在 go.mod 里生成, 如果 go. ...