Home  > Resources  > Blog

Demystifying ViewBag in ASP.NET MVC

September 7, 2015 by Faheem Javed
Category: Microsoft

In ASP.NET MVC you must have encountered ViewData and ViewBag. ViewData is the older implementation where as ViewBag is newer strict tpe checking based implementation. We can add items to ViewBag dynamically like this:

ViewBag.ProductId = 1;

ViewBag.ProductTitle = "Windows 10";

Even though we haven’t declared these properties before but yet we are able to declare them and assign values dynamically. How does it let us do that? To demystify it we have to understand ‘var’, ‘dynamic’ and ‘ExpandoObject’. So, let’s get started.


C# allows us to implicitly declare variables by using ‘var’ keyword. E.g.

int a=0; //explicitly declared variable

var b =0; //implicitly declared variable

We can also use ‘var’ keyword to create anonmous types / objects. E.g.

var bob = new { EmployeeId = 1, EmployeeName = "Bob", Department = "Sales" };

Even though we don’t have an Employee class we are still able to create Employee based objects by using Anonymous Type concept. If you write the above line in Visual Studio and hover mouse over ‘var’ keyword it will tell you that it’s an Anonymous Type. We can pass anonymous types to other. Anonymous objects can be passed to functions as parameters by using dynamic data type. E.g.


void DisplayEmployeeDetails(dynamic employee)


string message = string.Format("EmployeeId:{0}, EmployeeName:{1}, Department:{2}", employee.EmployeeId, employee.EmployeeName, employee.Department);



This is a very powerful concept since it lets us create dynamic objects on the fly and we can accept these in any function dynamically.


We can take this concept to next level by using another .NET Framework object called ExpandoObject which lets us create properties dynamically. E.g.

dynamic mixedBagObject = new ExpandoObject();

mixedBagObject.PlayerId = 1;

mixedBagObject.PlayerName = "Crosby";

mixedBagObject.CustomerId = 1;

mixedBagObject.CustomerDOB = new DateTime(1,1,1970);

mixedBagObject.ProductId = 1;

mixedBagObject.ProductTitle = "Windows 10";

Even though we have declared any class we are still able to create properties and assign them values on the fly.

So, ViewBag is actually a dynamic ExpandoObject.

Follow Us

Blog Categories