Viewbag
It is a dynamic object with properties created in the controller and accessible in the view, after which it disappears. It maintains the type of each member, although the compiler cannot do checks. It is usually the most appropriate.
ViewBag.Mensagem = "O que deseja passar aqui";
ViewBag.Valor = 1;
Consumption:
@ViewBag.Mensagem
@ViewBag.Valor
In fact in most cases a tuple or a type created for the specific purpose (viewmodel) It’s usually more appropriate in C#. It would be the case to pass some information isolated very simple and that does not belong to the data that should be included in the model of this view. It’s just my opinion, but I think I will go for the philosophy of C#. When you want this kind of flexibility you should use another language. I think the way you build these web applications leads to a lot biolerplate like this. But it is objectively used to pass "configuration" page data.
Viewdata
It is an object dictionary, and should only be used when it is not known what the composition of the object will be, since the elements do not have types and syntax of access to them a little uncomfortable. I think that in C# it doesn’t make much sense to use, I consider an obsolete resource, although it may be useful in some type of architecture.
ViewData["mensagem"] = "O que deseja passar aqui";
ViewData["valor"] = 1;
Consumption:
@(string)ViewData["mensagem"] //tecnicamente esta conversão pode ser feita automaticamente
@(int)ViewData["valor"] //a conversão não é necessária se apenas deseja imprimir
I put in the Github for future reference.
Tempdata
Here the goal is quite different. It’s a dictionary too, but its lifespan is that user’s session. It is only used to maintain value between calls in the controller and not to pass data to the view.
Remember that the vision is very connected to the controller, these above objects only serve to facilitate communication between them, are totally dispensable. Already the TempData
is more necessary, even if similar mechanisms exist. Without this mechanism or something like that, I would have to keep maintaining a status in the customer and transmit every time, running risks of safety and reliability. It is much more than a facilitator to send data, it has a whole infrastructure behind it that allows the "persistence" of data relevant to the session.