ViewBag in ASP.NET MVC

ViewBag in ASP.NET MVC Application

In this article, I am going to discuss the need and use ViewBag in ASP.NET MVC Application with examples. Please read our previous article before proceeding to this article where we discussed ViewData in the ASP.NET MVC application. As part of this article, we are going to discuss the following pointers which are 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 already discussed we can pass the data from a controller action method to a view using ViewData, ViewBag, TempData, and strongly typed model. Here in this article, I am going to show you how to use ViewBag to pass the 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.

ViewBag in ASP.NET MVC Application

As you can see in the above image, the ViewBag is a dynamic property (a new feature introduced in C# 4.0). Dynamic data type means at runtime based on the value, it will decide the data type. The ViewBag is also like ViewData which also transfers the data from a controller action method to a view.

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

As the ViewBag is operating on the new dynamic data type. The advantage is that we do not require typecasting while accessing the data from a ViewBag irrespective of the data that we are accessing.

ViewBag in ASP.NET MVC with String Type:

ViewBag in ASP.NET MVC with String Type

ViewBag in ASP.NET MVC with Complex Type:

ViewBag in ASP.NET MVC with Complex Type

Example of ViewBag in MVC Application:

Let us see an example to understand how to use the new dynamic type ViewBag in ASP.NET MVC Application to pass data from a controller action method to a view. We are going to work with the same example that we worked on in our previous article with ViewData. So, modify the Index action method of 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

Now we will see how to access the ViewBag data within an ASP.NET MVC view. So, modify the Index.cshtml view file as shown below.

@{
    Layout = null;
}
<!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 you can see, here we are accessing the data from the ViewBag using the same dynamic properties Header and Employee. Now run the application and navigate to the “/Home/Index” URL and you will see the data as expected on the webpage.

Note: The ViewBag is a dynamic property that is also resolved at runtime like ViewData; as a result, here also it will not provide compile-time error checking as well as intelligence support. For example, if we miss-spell the property names of the ViewBag, then we wouldn’t get any compile-time error rather we came to know about the error at runtime.

Internally, ViewBag is a wrapper around ViewData. So, it will throw a runtime exception if the ViewBag property name matches the key of ViewData.

Difference and Similarities between ViewData and ViewBag in ASP.NET MVC
  1. In ASP.NET MVC, we can use both ViewData and ViewBag to pass the data from a Controller action method to a View.
  2. The ViewData is a dictionary object whereas the ViewBag is a dynamic property. Both ViewData and ViewBag are used to create loosely typed views in ASP.NET MVC.
  3. In ViewData, we use the string as the key to store and retrieve the data whereas in ViewBag we use the dynamic properties to store and retrieve data.
  4. The ViewData requires typecasting for complex data types and also checks for null values to avoid any exceptions whereas ViewBag doesn’t require any typecasting for the complex data type.
  5. Both ViewData keys and ViewBag dynamic properties are resolved only at runtime. As a result, both do not provide compile-time error checking and because of this, we will not get any intelligence support.
  6. So if we misspell the key names or dynamic property names then we will not get any compile-time error rather we came to know about the error only at run time. This is the reason why we rarely used ViewBag and ViewData in our application.

The best and preferred approach in ASP.NET MVC Framework to pass data from a controller action method to a view is by using a strongly typed model. The strongly typed models provide compile-time error checking which in turn provides us the intelligence support.

In the next article, I am going to discuss the Strongly Typed Views in ASP.NET MVC application with Examples. Here, in this article, I try to explain the use of ViewBag in ASP.NET MVC application with examples. I hope this ViewBag in MVC article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.