Difference between ViewBag, ViewData, and ViewDataDictionary

In reality, both these values are passed via the ViewDataDictionary. Let’s look at that in more detail.

Technically, all data is passed from the controllers to the views via a ViewDataDictionary (a specialized dictionary class) called ViewData. You can set and read values to the ViewData dictionary using standard dictionary syntax, as follows:

ViewData["CurrentTime"] = DateTime.Now;

Although this continues to be available, ASP.NET MVC 3 leveraged the C# 4 dynamic keyword to allow for a simpler syntax. The ViewBag is a dynamic wrapper around ViewData. It allows you to set values as follows:

ViewBag.CurrentTime = DateTime.Now;

Thus, ViewBag.CurrentTime is equivalent to ViewData["CurrentTime"].

Generally, most current code you’ll encounter uses ViewBag rather than ViewData. For the most part, you don’t have a real technical advantage when choosing one syntax over the other. ViewBag is just syntactic sugar that some people prefer over the dictionary syntax. It just looks nicer.

ViewDataDictionary is a specialized dictionary class, not just a generic Dictionary. One reason for this is that it has an additional Model property that allows for a specifi c model object to be available to the view. Because you can only have one model object in ViewData, using this to pass a specifi c class to the view is convenient. This allows your view to specify the class it is expecting the model object to be, which means you can take advantage of strong typing.

VIEWDATA and VIEWBAG:

Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes.

One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile.

Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method.

If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the value to a specifi c type: (string)ViewBag.Name.