Differences between viewData, viewBag, and templateData in ASP. net mvc: viewdataviewbag
I. Type comparison
1.1) ViewBag is a dynamic type (dynamic ).
1.2) ViewData is a Dictionary type --> TempDataDictionary.
1.3) TempData is a Dictionary --> ViewDataDictionary.
Ii. lifecycle and scope
2.1) the life cycle of ViewBag is the same as that of View. It can only act on one View.
2.2) the life cycle of ViewData is the same as that of View. Only one View can be used.
2.3) the lifecycle of TempData exists until it is called, but the value after one call is deleted and can be passed in different actions.
TempData is stored in the Session. When the Controller executes a request, it first obtains TempData from the Session, then clears the Session, and obtains TempData. Although it is saved in an internal dictionary object, however, after each entry in the set is accessed once, it is deleted from the dictionary table. At the specific code level, the TempData acquisition process is to read data from the Session of ControllerContext through the SessionStateTempDataProvider. LoadTempData method, and then clear the Session. Therefore, TempData can be transferred only once across the Controller.
Iii. Differences
3.1) viewBag does not require data conversion
Controller: ViewBag. key = new Dictionary <string, string> ();
View:
@ Foreach (var item in ViewBag. key)
{
@ Item;
}
3.2) the data type to be converted is required to be queried in ViewBag.
Controller: ViewData ["key"] = new Dictionary <string, string> () {"key1", "value1" },{ "key2", "value2 "}};
View:
@ Foreach (var item in ViewData ["key"] as Dictionary <string, string>)
{
@ Item;
}
3.3) Use TempData is the same as ViewBag, but note that the value of TempData is automatically cleared once it is called.