Topic: ViewBag versus ViewData
Description: ViewBag is new to C# 4.0. It is a dynamic feature that is like the ViewData in that it should only be used to persist temporary or small amounts of data. You should still try using proper View models.
Notes: From a personal standpoint, you should try to avoid using ViewBag or ViewData in a true Enterprise level application and use a strongly typed object (ViewModel). This will also lead to better testing.
ViewData is a collection of key/value pairs, where viewbag is a dynamic object implementation of viewdata
ViewData
- Dictionary of Key/Value pairs (collection)
- Been around since first MVC implementation
- Will work in .Net Framework 3.5 and above
- Faster withn compared to ViewBag
- When using on the page, proper type casting is required
Example:
Controller ---
ViewData["Welcome"] = "My Welcome Message";
View ---
<%: ViewData["Welcome"]%>
ViewBag
- A dynamic type object
- Introduced in MVC 3.0
- Will work in .Net Framework 4.0 and above
- Slower than ViewData
- When using on a page, type casting is not required
Example:
Controller ---
ViewBag.Message = "My Welcome Message";
View ---
<%: ViewBag.Message %>