Premium Only Content
Part 6 ViewData and ViewBag in mvc
In this video we will discuss
1. What is ViewData
2. What is ViewBag
3. Difference between ViewData and ViewBag
Both ViewData and ViewBag are used to pass data from a controller to a view. ViewData is a dictionary of objects that are stored and retrieved using strings as keys. The syntax of ViewData is very similar to that of ViewState, SessionState and ApplicationState.
// Storing data in ViewData
ViewData["YourData"] = "SomeData";
// Retrieving data from ViewData
string strData = ViewData["YourData"].ToString();
ViewData does not provide compile time error checking. For example, if you mis-spell the key names you wouldn't get any compile time error. You get to know about the error only at runtime.
ViewBag uses the dynamic feature that was introduced in to C# 4. It allows an object to have properties dynamically added to it. Using ViewBag the above code can be rewritten as below.
// Storing data in ViewBag
ViewBag.YourData = "SomeData";
// Retrieving data from ViewBag
string strData = ViewBag.YourData;
Just like ViewData, ViewBag does not provide compile time error checking. For example, if you mis-spell the property name, you wouldn't get any compile time error. You get to know about the error only at runtime.
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Please Note: To pass data from controller to a view, It's always a good practice to use strongly typed view models instead of using ViewBag & ViewData. Strongly typed view models provide compile time error checking. We will discuss view models in a later video session.
-
LIVE
Nerdrotic
4 hours ago $9.74 earnedUS Congress UFO Hearing LIVE REACTION with Chris Gore | Forbidden Frontier #081
2,725 watching -
LIVE
The Charlie Kirk Show
1 hour agoTear It Down, Build It Up + The Military in Crisis | Huckabee, Prince, Davis | 11.13.24
17,976 watching -
LIVE
Akademiks
1 hour agoKendrick Lamar Announces He Will Headline Superbowl 2025. Clowns Drake w/ sayin 'NO ROUND 2s'
3,029 watching -
20:38
Misha Petrov
37 minutes agoLeftist LUNATICS Can’t ACCEPT Trump’s Win! Uncovering Their Darkest WARNINGS to Trump Voters
26 -
LIVE
GameLeap RAID Shadow Legends
34 minutes agoWE SOLVED SAND DEVIL! Top Tips Every New Player Needs - Raid Shadow Legends
76 watching -
LIVE
Grant Stinchfield
1 hour agoBallot Dumps, More Voters than Registered, Even Deleted Votes,,, It Looks Very Fishy!
902 watching -
1:02:21
The Dan Bongino Show
4 hours agoTrump Makes His BOLDEST Moves Yet (Ep. 2370) - 11/13/2024
668K1.99K -
1:02:59
The Rubin Report
3 hours agoCNN Host Forced to Intervene as Guest Loses His Cool as Republican Calmly States Facts
72.6K45 -
The Boomer Effect
19 hours agoSocial Security - Simple and Smart
50 -
24:06
Rethinking the Dollar
3 hours agoDigital Illusions of Wealth: Why Real Silver Matters More Than Ever!
3691