ViewBag in ASP.NET MVC

ViewBag in ASP.NET MVC

ViewBag in ASP.NET MVC Application

In this article, I will explain the necessity and usage of ViewBag in an ASP.NET MVC application with practical examples. Before diving into this topic, I recommend going through our previous article, where we explored ViewData in ASP.NET MVC. Throughout this discussion, we will cover key aspects related to MVC ViewBag.

1.What is ViewBag in ASP.NET MVC?
2.How to Pass and Retrieve data From ViewBag in ASP.NET MVC?
3.Example of ViewBag in MVC.
4.What are the Difference and Similarities between ViewData and ViewBag in ASP.NET MVC?

As we have already discussed, data can be passed from a controller action method to a view using ViewData, ViewBag, TempData, and a strongly typed model. In this article, I will demonstrate how to utilize ViewBag to transfer data from a controller action method to a view.

What is ViewBag in ASP.NET MVC?

The ViewBag in ASP.NET MVC Framework is one of the mechanisms to pass the data from a controller action method to a view. If you go to the definition, of ViewBag, then you will see that it is defined as a property in the ControllerBase class with the following signature.

As shown in the image above, ViewBag is a dynamic property introduced in C# 4.0. A dynamic data type determines its type at runtime based on the assigned value. Similar to ViewData, ViewBag is used to transfer data from a controller action method to a view.

How to Pass and Retrieve data From ViewBag in ASP.NET MVC?

Since ViewBag operates on the dynamic data type, one key advantage is that typecasting is not required when accessing data, regardless of the type of data being retrieved.

ViewBag in ASP.NET MVC with String Type:
ViewBag in ASP.NET MVC with Complex Type: Example of ViewBag in MVC Application:

Let’s explore an example to understand how to use the **dynamic type ViewBag** in an **ASP.NET MVC** application to **pass data from a controller action method to a view**. We will be working with the same example used in our previous article on **ViewData**. Now, update the Index action method of the HomeController class as shown below.



using FirstMVCDemo.Models;
using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
            Employee employee = employeeBL.GetEmployeeDetails(101);
            
            ViewBag.Employee = employee;
            ViewBag.Header = "Employee Details";
            
            return View();
        }
    }
}
                                           

As you can see in the above example, here we are using ViewBag to pass the data.


Accessing the ViewBag in a View in ASP.NET MVC

Next, let's learn how to retrieve ViewBag data in an ASP.NET MVC view. Update the Index.cshtml file as demonstrated below.


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Page Title</title>  
</head>
<body>
       @{
        var employee = ViewBag.Employee;
        }
    <h2><@ViewBag.Header ></h2>
    <table style="font-family:Arial">
        <tr>
            <td>Employee ID:</td>
            <td><@employee.EmployeeId></td>
        </tr>
        <tr>
            <td>Name:</td>
            <td><@employee.Name></td>
        </tr>
        <tr>
            <td>Gender:</td>
            <td><@employee.Gender></td>
        </tr>
        <tr>
            <td>City:</td>
            <td><@employee.City></td>
        </tr>
        <tr>
            <td>Salary:</td>
            <td><@employee.Salary></td>
        </tr>
        <tr>
            <td>Address:</td>
            <td><@employee.Address></td>
        </tr>
    </table>
</body>
</html>
                                            

As shown above, we retrieve data from ViewBag using its dynamic properties, Header and Employee. Now, run the application and navigate to "/Home/Index" in the browser. You should see the expected data displayed on the webpage.


Note:Since ViewBag is a dynamic property resolved at runtime, it behaves similarly to ViewData. This means it doesn't offer compile-time error checking or intellisense support. For instance, if there is a typographical error in the property names of ViewBag, it won't trigger a compile-time error. Instead, the issue will only be discovered when the application runs.



Internally, ViewBag acts as a wrapper around ViewData. Therefore, if the ViewBag property name coincides with a ViewData key, it will result in a runtime exception.


  1. In ASP.NET MVC, both ViewData and ViewBag can be used to transfer data from a controller action method to a view.
  2. ViewData is a dictionary object, while ViewBag is a dynamic property.
  3. Both ViewData and ViewBag are used to create loosely typed views in an ASP.NET MVC application.
  4. In ViewData, a string key is used to store and retrieve data, whereas in ViewBag, dynamic properties are used for storing and accessing data.
  5. ViewData requires typecasting for complex data types and also checks for null values to prevent exceptions. In contrast, ViewBag does not require typecasting for complex data types.
  6. Both ViewData keys and ViewBag properties are evaluated only at runtime. Therefore, neither provides compile-time error checking, and as a result, there is no support for intellisense.
  7. If the key names or dynamic property names are misspelled, there will be no compile-time error. The error will only be discovered when the application is running.
  8. This is why ViewBag and ViewData are rarely used in applications.

The most effective and recommended method in the ASP.NET MVC framework for passing data from a controller action method to a view is by using a strongly typed model. Strongly typed models offer compile-time error checking, which in turn ensures intelligence support.


In the upcoming article, I will cover the topic of Strongly Typed Views in an ASP.NET MVC application, complete with examples. In this article, I have explained how to use ViewBag in an ASP.NET MVC application, with practical examples. I hope this article on ViewBag in MVC has been helpful for your needs. I would love to hear your feedback. Please feel free to share your comments, questions, or suggestions about this article.