What are the differences between ViewBag, ViewData, and TempData?

4

I was researching how to pass data to a view , or rather persist the data of a controller to the view .

I would like to know among the 3 ways mentioned in the title:

  • What are the differences between them?
  • In which cases is the use of one more recommended than another?
asked by anonymous 01.02.2018 / 15:12

1 answer

4

ViewBag

It is a dynamic object with properties created in the controller and that is accessible in the view, after which it disappears. It maintains the type of each member, although the compiler can not make 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 ) is usually more appropriate in C #. It would be the case to pass some very simple isolated information that does not belong to the data that must be included in the model of this vision. It's just my opinion, but I think gambiarra to the C # philosophy. When this type of flexibility is desired, it should use another language. I think the way we build these web applications leads to much biolerplate like this. But objectively it is used to pass page "configuration" data.

ViewData

It is a dictionary of objects, and should only be used when you do not know the composition of what will be the object, since the elements do not have types and syntax of access to them a little uncomfortable. I think in C # it does not make much sense to use, I consider it an obsolete resource, although it may have utility 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

TempData

Here the goal is quite different. It's a dictionary too, but its lifetime is that user's session. It is used only to hold value between calls in the controller and not to pass data to the view.

Remember that the view is very attached to the controller, these objects only serve to facilitate communication between them, are totally expendable. Since TempData is more necessary, although there are other similar mechanisms. Without this mechanism or something like that it would have to remain in the client's state and be transmitting at all times, at the risk of security and reliability. It is much more than a facilitator to send data, it has a whole infrastructure behind it that allows the "data persistence" relevant to the session.

    
01.02.2018 / 16:10