Differences between viewData, viewBag, and templateData in ASP. net mvc: viewdataviewbag

Source: Internet
Author: User

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> ();


@ 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 "}};


@ 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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.