How does the ASP.NET MVC's ViewBag
work? MSDN says it is just an Object
, which intrigues me, how does "Magic" properties such as ViewBag.Foo
and magic strings ViewBag["Hello"]
actually work?
Also, how can I make one and use it in my ASP.NET WebForms app?
Examples would be really appreciated!
The
ViewBag
is anSystem.Dynamic.ExpandoObject
as suggested. The properties in theViewBag
are essentiallyKeyValue
pairs, where you access the value by the key. In this sense these are equivalent:It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.
If you wanted to use this for web forms, add a dynamic property to a base page class like so:
Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:
That should work. If not, there are ways to work around it.
ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......
In view
What I have learnt is that both should have the save dynamic name property ie ViewBag.victor
ViewBag is of type dynamic. More, you cannot do
ViewBag["Foo"]
. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.Internal implementation of
ViewBag
actually stores Foo intoViewData["Foo"]
(type of ViewDataDictionary), so those 2 are interchangeable.ViewData["Foo"]
andViewBag.Foo
.And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.
ViewBag is used to pass data from Controller Action to view to render the data that being passed. Now you can pass data using between Controller Action and View either by using ViewBag or ViewData. ViewBag: It is type of Dynamic object, that means you can add new fields to viewbag dynamically and access these fields in the View. You need to initialize the object of viewbag at the time of creating new fields.
e.g: 1. Creating ViewBag: ViewBag.FirstName="John";