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 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 will discuss the following pointers.

  1. What is ViewBag in MVC?
  2. How do you Pass and Retrieve data from ViewBag in ASP.NET Core MVC?
  3. When to Use ViewBag in Real-Time Applications.
  4. Difference Between ViewData and ViewBag in ASP.NET Core MVC.
  5. Advantages and Disadvantages of 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 a dynamic property that provides a convenient way to add a small amount of data that doesn’t require strongly typed views.

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 do you 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 the data type will be decided at runtime based on the right-hand side values. 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 the 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, 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, it will not provide compile-time error checking or intelligence support. For example, if we misspell the property names of the ViewBag, then we won’t get any compile-time error. Rather, we came to know about the error at runtime.

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, one-off pieces of data to a view, like page titles, breadcrumbs, or small messages, ViewBag can be a straightforward choice.
  • Displaying Messages or Notifications: It’s often used for sending feedback messages to a view, like success, error, or information messages after form submissions.
  • Setting Layout Properties: ViewBag can be useful for setting properties that are used in layout views, such as the current active menu item or user-specific information.
  • Dynamic Content: When the data structure is not fixed, and you want to pass dynamic content that does not fit well into a strongly typed model,
When not to use ViewBag in ASP.NET Core MVC?
  • Large or Complex Data: For complex data or large datasets, using ViewBag can reduce clarity and make debugging more difficult. In such cases, it’s better to use strongly typed view models.
  • Strongly-Typed Views: If you need type safety and compile-time checking, ViewBag is not the right choice as it is dynamic and bypasses compile-time type checking.
  • Repeated Use of Data: If the same data is used in many places, including it in a view model is better to avoid duplication and potential inconsistency.
Advantages of ViewBag in ASP.NET Core MVC
  • Dynamic Nature: ViewBag is dynamic, which means you don’t need to define a strongly typed view model for every piece of data you want to pass to the view. This can simplify coding in scenarios where the data structure is simple or constantly changing.
  • Ease of Use: It’s straightforward to use. You can easily assign values to ViewBag in a controller and retrieve them in a view without requiring explicit type casting.
  • Flexibility: ViewBag can hold any type of data, which makes it flexible for various use cases.
  • Good for Small Applications: It’s useful for small to medium-sized applications where defining view models for every little piece of data can be overkill.
Disadvantages of ViewBag in ASP.NET Core MVC
  • Lack of Compile-Time Error Checking: Since ViewBag is dynamic, errors related to it (like misspelling a property name) are not caught at compile time. This can lead to runtime errors that are harder to debug.
  • No IntelliSense Support: Due to its dynamic nature, ViewBag does not provide IntelliSense support in IDEs. This can slow down development and increase the chance of errors.
  • Performance Overhead: The dynamic operations involved with ViewBag can lead to a slight performance overhead compared to strongly typed view models.
  • Not Suitable for Complex Data Structures: ViewBag is good for passing simple data, but it’s not suitable for complex data structures, especially those requiring validation or business logic processing.
Difference Between ViewData and ViewBag in ASP.NET Core MVC

In ASP.NET Core MVC, both ViewData and ViewBag are used to pass data from a controller to a view, but they have some key differences in their implementation and usage:

Type:
  • ViewData: It is a dictionary of objects derived from the ViewDataDictionary class. It requires typecasting for complex data types and checks for null values to avoid errors.
  • ViewBag: It is a dynamic property (a wrapper around ViewData) that provides a dynamic view over the ViewDataDictionary. It allows you to create properties dynamically.
Syntax and Usage:
  • ViewData: Accessed using strings as keys (e.g., ViewData[“Key”] = value;). Since it’s a dictionary, you need to cast the data to the correct type when retrieving it in the view.
  • ViewBag: Allows more straightforward syntax using dynamic properties (e.g., ViewBag.MyProperty = value;). No casting is needed when retrieving the data.
Error Handling:
  • ViewData: If you try to retrieve a key that doesn’t exist, it will return null, and you have to handle possible null values. Incorrect casting can lead to runtime errors.
  • ViewBag: If you try to use a property that doesn’t exist, it will return null. However, since it’s dynamic, you won’t get compile-time error checking, which can sometimes lead to runtime errors that are harder to trace.
Performance:
  • Both ViewData and ViewBag have similar performance characteristics, as ViewBag is a wrapper around ViewData. However, the dynamic nature of ViewBag can potentially make it slightly slower due to overheads in dynamic resolution, though this is usually negligible in most applications.
IntelliSense and Compile-Time Checking:
  • ViewData: It does not provide IntelliSense support in views since it uses strings as keys. Also, there’s no compile-time type checking.
  • ViewBag: It also does not support IntelliSense, and because it is dynamic, it bypasses compile-time type checking.
Choosing Between ViewData and ViewBag
  • Use ViewData when you are comfortable with key-based access and prefer a dictionary-like structure.
  • Use ViewBag for more readability and ease of use due to its dynamic properties.

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 *