ViewBag in ASP.NET Core MVC

ViewBag in ASP.NET Core MVC Application

In this article, I will discuss the use of ViewBag in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing ViewData in ASP.NET Core MVC Applications. As discussed in the ASP.NET Core MVC application, we can pass data from a controller to a view using ViewData, ViewBag, TempData, and a Strongly Typed View Model. 

What is ViewBag in ASP.NET Core MVC?

In ASP.NET Core MVC, ViewBag is a dynamic object that provides a way to pass data from the controller action method to the view. It allows us to create properties dynamically on the fly and add properties to the ViewBag object in the controller actions, which are then accessible in the Razor views. ViewBag is useful for passing simple data (e.g., strings, dates) that do not require a strongly typed view model. If you go to the Controller abstract class, you will find the following signature of the ViewBag property.

ViewBag in ASP.NET Core MVC

So, in the ControllerBase class, which is the base class for controllers in ASP.NET Core MVC, as you can see, there’s a property called ViewBag, which is a type of DynamicViewData. This DynamicViewData is a dynamic object that allows properties to be dynamically added at runtime.

Note: The dynamic type is introduced in C# 4.0. It is very similar to the var keyword, which means we can store any value in it, but the type will be decided at run time rather than compile time.

How Do We Pass and Retrieve Data from ViewBag in ASP.NET Core MVC?

So, when we set a property on ViewBag in a controller action, like ViewBag.Header= “Student Details”; DynamicViewData internally adds or updates a property with the name “Header” and the value “Student Details” like dynamic Header = “Student Details”. Based on the right-hand side value, the data type will be decided at runtime. For example, if the value is a string, the data type will be considered a string at runtime.

In a Razor view file (.cshtml), we can access the properties set in ViewBag directly using the @ symbol followed by the property name (@ViewBag.Header ). This dynamic access is possible because ViewBag is of type dynamic.

How to Access Data from ViewBag in ASP.NET Core MVC with String Type:

ViewBag in ASP.NET Core MVC with String Type

How to Access Data from ViewBag in ASP.NET Core MVC with Complex Type:

ViewBag in ASP.NET Core MVC with Complex Type

Since ViewBag is dynamic, accessing a property that doesn’t exist or is not set will not throw a compile-time error. Instead, it will result in a runtime NullReferenceException if the property is accessed without being set.

The data stored in ViewBag is available only during the current request lifecycle. Once the view is rendered and sent to the client, ViewBag data is no longer accessible.

Because ViewBag uses dynamic, there is no compile-time type checking. If property names are mistyped or changed without updating all references, this can lead to potential runtime errors.

Example to Understand ViewBag in ASP.NET Core MVC Application:

Let us see an example of using ViewBag to pass data from a controller action method to a view in the ASP.NET Core MVC Application. We will work with the same example we worked on in our previous article with ViewData. So, modify the Details action method of the HomeController class as shown below.

using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Details()
        {
            ViewBag.Title = "Student Details Page";
            ViewBag.Header = "Student Details";
            Student student = new Student()
            {
                StudentId = 101,
                Name = "James",
                Branch = "CSE",
                Section = "A",
                Gender = "Male"
            };

            ViewBag.Student = student;

            return View();
        }
    }
}

As you can see in the above example, here we are using the dynamic properties Title, Header, and Student on the ViewBag. 

Accessing ViewBag in a View in ASP.NET Core

Now, we will see how to access the ViewBag data within a View in MVC Application. So, modify the Details.cshtml view file as shown below. Here, you can see we are directly accessing the string and complex type values without typecasting, and this is possible because of the dynamic data type.

@{
    Layout = null;
    var student = ViewBag.Student;
}
<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1>@ViewBag.Header</h1>
    <div>
        StudentId : @student?.StudentId
    </div>
    <div>
        Name : @student?.Name
    </div>
    <div>
        Branch : @student?.Branch
    </div>
    <div>
        Section : @student?.Section
    </div>
    <div>
        Gender : @student?.Gender
    </div>
</body>
</html>

As you can see, we are accessing the data from the ViewBag using the same dynamic properties: Title, Header, and Student. Now run the application and navigate to the “/Home/Details” URL, and you will see the data as expected on the webpage, as shown in the image below.

ViewBag in ASP.NET Core MVC

When should you use ViewBag in ASP.NET Core MVC?

Here are some scenarios when you might use ViewBag:

  • Passing Simple Data to Views: If you need to pass simple data to a view, like Page Titles, Headers, or small messages, ViewBag can be a straightforward choice.
  • Displaying Messages or Notifications: This is used for sending feedback messages to a view, such as success, error, or information messages after form submissions.
Differences Between ViewBag and ViewData in ASP.NET Core MVC

In ASP.NET Core MVC, both ViewBag and ViewData are mechanisms to pass data from controllers to views, but they have some key differences in how they work and their usage:

Type Safety:
  • ViewBag: It uses dynamic to store data, so there’s no compile-time type checking. This means you can set and access properties dynamically, but you may encounter runtime errors if the property name is mistyped or if the types don’t match.
  • ViewData: It uses a Dictionary<string, object> to store key-value pairs. While not type-safe at compile-time, you have to cast values when retrieving them ((string)ViewData[“Message”]). This provides slightly more safety compared to ViewBag.
Usage and Syntax:
  • ViewBag: Accessed using dot notation (@ViewBag.Message) in Razor views. Properties are set directly (ViewBag.Message = “Hello”;) in the controller actions.
  • ViewData: Accessed using a key (@ViewData[“Message”] as string) in Razor views. Properties are set using Key-Value Pait to ViewBag (ViewData[“Message”] = “Hello”;) in controller actions.
Scope and Lifetime:
  • Both ViewBag and ViewData are available during the current request. They are typically used to pass data from controllers to views within the same request lifecycle.
Error Handling:
  • ViewBag: Due to its dynamic nature, errors like null references or type mismatches might occur at runtime if not handled carefully.
  • ViewData: Requires explicit casting when retrieving values, which can help catch type mismatches earlier.
When to Use:
  • ViewData: We need to use ViewData when working within loops or conditional logic where dictionary operations are more straightforward.
  • ViewBag: We need to use ViewBag when we want cleaner syntax and are dealing with a very small amount of data that does not require type-checking.

In the next article, I will discuss the Strongly Typed Views in ASP.NET Core MVC Applications with Examples. In this article, I try to explain ViewBag in the ASP.NET Core MVC application. I hope this article will help you with your needs.

3 thoughts on “ViewBag in ASP.NET Core MVC”

Leave a Reply

Your email address will not be published. Required fields are marked *