ViewBag in ASP.NET Core MVC

ViewBag in ASP.NET Core MVC Application

In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC Applications with Examples. Please read our previous article before proceeding to this article, where we discussed the ViewData in ASP.NET Core MVC Application. As we already discussed in the ASP.NET Core MVC application, we can pass the data from a controller to a view using ViewData, ViewBag, TempData, and Strongly Typed View Model. As part of this article, we are going to discuss the following pointers.

  1. What is ViewBag in MVC?
  2. How to Pass and Retrieve Data From ViewBag in ASP.NET Core MVC?
  3. Example to understand ViewBag in ASP.NET Core MVC Application.
  4. Difference between ViewData and ViewBag in ASP.NET Core MVC
What is ViewBag in ASP.NET Core MVC?

In ASP.NET Core MVC, ViewBag is a dynamic property that provides a convenient way to pass data from a controller action to its corresponding view. It’s similar to ViewData in that it allows you to send data from the controller to the view, but ViewBag uses a more concise syntax and is easier to use for simple scenarios.

The ViewBag in MVC is one of the mechanisms to pass the data from a controller action method to a view. If you go to the Controller abstract class, then you will find the following signature of the ViewBag property.

ViewBag in ASP.NET Core MVC

So the ViewBag is a dynamic property of the Controller abstract class. The dynamic type is introduced in C# 4.0. It is very much 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. The ViewBag transfers the data from the controller action method to a view only. The reverse is not possible.

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

The point that you need to keep in mind is that ViewBag is operating on the dynamic data type. So we don’t require typecasting while accessing the data from a ViewBag. It does not matter whether the data that we are accessing is of type string or any complex type.

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

Note: Dynamic Data Types means, based on the right-hand side values, at runtime, the data type will be decided. So, we don’t require typecasting if we use ViewBag.

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

Let us see an example to understand how to use ViewBag to pass data from a controller action method to a view in 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 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, here 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 below image.

ViewBag in ASP.NET Core MVC

The ViewBag is a dynamic property that is resolved at runtime; 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.

Key points to remember about ViewBag:
  1. Dynamic Property: ViewBag uses a dynamic property syntax, which means you don’t need to cast the values when accessing them in the view.
  2. Type Safety: Since ViewBag uses dynamic typing, there’s no compile-time type checking. Incorrect property names or types can lead to runtime errors.
  3. Less Verbose: Compared to ViewData, ViewBag provides a more concise and readable way to pass data from controllers to views.
  4. Lifetime: Like ViewData, the data stored in ViewBag is available only for the duration of the current request-response cycle.
  5. Quick Data Passing: ViewBag is suitable for quick and simple scenarios where you want to pass a small amount of data from the controller to the view without the need for a dedicated ViewModel class.
  6. No Intellisense Support: ViewBag doesn’t have Intellisense support in the same way strongly typed models do because of its dynamic nature.

While ViewBag can be handy for passing small amounts of data, for more complex scenarios, using strongly typed models (ViewModels) is generally recommended because it offers better type safety, code organization, and maintainability.

Difference Between ViewData and ViewBag in ASP.NET Core MVC
  1. In 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 weakly typed dictionary object, whereas the ViewBag is a dynamic property. Both ViewData and ViewBag are used to create a loosely typed view in ASP.NET Core MVC Application.
  3. In ViewData, we use string keys to store and retrieve the data from the ViewData dictionary, whereas in ViewBag, we use the dynamic properties to store and retrieve data.
  4. Both the 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.
  5. So if we misspell the key or dynamic property names, 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 use ViewBag and ViewData in our application.

The best and preferred approach in ASP.NET Core MVC Application to pass data from a controller action method to a view is by using a strongly typed model object. When we use a strongly typed model object, only our view becomes a strongly typed one. In the next article, I am going to discuss the Strongly Typed Views in ASP.NET Core MVC Applications with Examples. Here, in this article, I try to explain ViewBag in ASP.NET Core MVC application. I hope this article will help you with your needs.

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

Leave a Reply

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