问题描述
我正在读一本关于ASP.NET MVC,我想知道下面的例子是如何工作的:
I am reading a book on ASP.NET MVC and I'm wondering how the following example works:
public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
}
查看
<h1>@ViewBag.MyProperty</h1>
现在我明白 ViewBag
是一个动态的对象,所以这就是你如何设置属性(虽然我不知道很多关于动态对象,从来没有与他们合作)。但如何将视图控制器获得 ViewBag
的具体实例,尽管我们不直接传递什么?
Now I understand that ViewBag
is a dynamic object, so that's how you can set the property (though I don't know much about dynamic objects, never worked with them.) But how does the view get the specific instance of the ViewBag
from the controller, even though we don't pass anything directly?
我认为 ViewBag
可以是一个公共
静态
对象,但任何改变,将是全球性的,它不会具体到一个视图实例。
I thought that the ViewBag
could be a public
static
object, but then any change to it would be global and it wouldn't be specific to a view instance.
您能否详细说明为如何在幕后工作?
Could you elaborate as to how this works behind the scenes?
public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
public ActionResult Index2()
{
ViewBag.MyProperty = 6;
return View();
}
}
现在让我们假设首页
方法首先调用,那么索引2
。最终 ViewBag.MyProperty
的价值将最终成为6(一般为从索引2
值)。我觉得这是不是做了件好事,但在同一时间,我觉得我想在桌面开发方面。也许在ASP.NET MVC中使用时,它并不重要,因为网络是无状态的。 是这样的话?
Now let's say the Index
method is called first, and then the Index2
. In the end the value of ViewBag.MyProperty
will end up as 6 (the value from Index2
). I feel that it is not a good thing to do, but at the same time I feel that I'm thinking in desktop development terms. Maybe it doesn't matter when used with ASP.NET MVC, as the web is stateless. Is this the case?
推荐答案
ViewBag
是 ControllerBase
的属性,所有控制器都必须继承。这是一个动态
对象,这就是为什么你可以没有得到编译时错误,将其添加新的属性。
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.
的查看
(及其变种)方法不是静态
为好,这是怎样的看法接收在 ViewBag
值:渲染视图的过程中,控制器实例都有ViewBag实例以及
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.
这篇关于如何在ViewBag ASP.NET MVC在幕后工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!