1.

Explain ViewBag, ViewData and TempData?

Answer»

ASP.NET MVC has provided ViewBag and VIEWDATA to transfer data from the controller to view. Let’s look into these in deep:

ViewData: ViewData is derived from the ViewDataDictionary, hence it stores data in key Value format like a dictionary, where the Keys are in String and represents the name of an object while Values will be objects. As data in ViewData is stored in object form, so it is required to cast the data to its original type before USING it. It is also required to do the NULL check while retrieving data. The life span of ViewData is from Controller to View.

Example: ViewData["Message"] = "TEST Data";

ViewBag: ViewBag is a Wrapper that is built around the ViewData. It is a DYNAMIC property and it makes use of the C# 4.0 dynamic FEATURES. Like ViewData, it is not required to do typecasting data before use. The life span of ViewBag is from Controller to View only.

Example: ViewBag.Message = "Test Data";

TempData: TempData is derived from TempDataDictionary class and it is also a  Dictionary object i.e. Keys and Values where Keys are in String and represents the name of the object while Values will be objects. It is required to do typecasting of data before using it as the data is in the object format and it also requires NULL checks while retrieving. The life span of TempData is larger than of ViewData and ViewBag. TempData can be used for passing value from Controller to View and from Controller to Controller. It is also available for Current and Subsequent Requests. 

Example: TempData["Message"] = "Test temp data";



Discussion

No Comment Found