Back to: ASP.NET Core Tutorials For Beginners and Professionals
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. When building dynamic web applications using ASP.NET Core MVC, you often need to pass small pieces of data from your controllers to your views. ASP.NET Core MVC offers multiple methods for passing data from a Controller to a View. One such convenient and widely used method is ViewBag.
What is ViewBag in ASP.NET Core MVC?
ViewBag is a dynamic property of the Controller base class in ASP.NET Core MVC that allows you to pass data from a Controller to its corresponding View in a flexible and easy-to-use way. It allows us to attach data to our controller (ViewBag property of the controller), which is then available for use in the corresponding view.
- Dynamic Property: You don’t need to define types or keys as strings. Instead, you can add new properties on the fly, like ViewBag.Message = “Hello World”.
- Wrapper Around ViewData: Internally, ViewBag is implemented as a wrapper around the ViewData dictionary, so both share the same underlying data. This means anything you add to ViewBag can be accessed through ViewData and vice versa.
- Scope: Just like ViewData, ViewBag data lasts only for the duration of the current HTTP request. It is not persisted between multiple requests.
What does “dynamic” mean here?
The dynamic type was introduced in C# 4.0. It behaves somewhat like the var keyword in that it can hold any type of value, but with a key difference: the actual type is resolved at runtime rather than compile time. This provides flexibility but sacrifices compile-time type checking.
How to Access Data from ViewBag in ASP.NET Core MVC with String Type:
You can set and access a string (or other simple types) on ViewBag directly. You don’t need to cast or use any string key; just reference the property name you set. The example is given below:
How to Access Data from ViewBag in ASP.NET Core MVC with Complex Type:
You can also store objects (like a Student model) in ViewBag. Because ViewBag is dynamic, you can access properties on the complex object directly, without type casting. The example is given below:
Important Note: If you try to access a ViewBag property that wasn’t set, you’ll get a null value. Trying to access a property on null will cause a NullReferenceException at runtime. There’s no compile-time warning or IntelliSense support for property names on ViewBag.
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 use the same example that we created in our ViewData example. Please ensure to have the following Student model within the Models folder. This model represents a student entity with multiple properties.
namespace FirstCoreMVCWebApplication.Models { public class Student { public int StudentId { get; set; } public string? Name { get; set; } public string? Branch { get; set; } public string? Section { get; set; } public string? Gender { get; set; } } }
Modifying the Home Controller:
We want to display a page showing student details. Please modify the HomeController as follows. Here, we dynamically add Title, Header, and Student properties to the ViewBag and assign corresponding values.
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(); } } }
Accessing ViewBag in a View
Now, we will see how to access the ViewBag data within a View. Please 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>
Running the Application:
Now, run the application and navigate to the “/Home/Details” URL. You will then see the data as expected on the webpage, as shown in the image below.
Important Notes About ViewBag
- Dynamic, Not Type-Safe: ViewBag does not provide compile-time type checking or IntelliSense support. If you misspell a property or try to access a property that wasn’t set, you will only know at runtime (can result in a NullReferenceException).
- Scope: Data in ViewBag is only valid for the current request. It cannot be used for redirects or persist between requests.
- Great for Small, Temporary Data: Ideal for passing simple data, such as messages, titles, flags, or a small object, to a view or layout.
- Not for Complex Apps: For large applications or when passing lists or complex data, it is better to use strongly typed models for safety and maintainability.
Differences Between ViewBag and ViewData in ASP.NET Core MVC
Though both ViewBag and ViewData serve the same purpose, passing data from Controller to View, they differ mainly in how you access and use them:
Type:
- ViewData is a dictionary (ViewDataDictionary) accessed via string keys.
- ViewBag is a dynamic object that allows property-like access.
Syntax:
- ViewData requires string keys and casting when retrieving data.
- ViewBag offers simpler syntax without the need for casting.
Usage:
- ViewData is more complex and requires explicit casting.
- ViewBag is more concise and easier to use, especially for small data.
Internals:
- ViewBag is a wrapper around ViewData, so data stored in one can be accessed by the other.
- If you store data using ViewBag, you can access it using ViewData.
- Similarly, if you store the data using ViewData, you can still access the data using ViewBag.
Type Safety:
- Neither is type-safe, but ViewBag is more readable due to its dynamic nature.
When to Use ViewData
- ViewData is useful when you need to work with data in a dictionary-like structure, especially in scenarios involving loops or conditional logic where dictionary operations (like checking for keys, adding, or removing entries) are more straightforward.
- Since ViewData is a ViewDataDictionary, you can use methods like .ContainsKey(), .Remove(), or .Keys that can be handy in more dynamic data scenarios.
- Use ViewData when you might want to pass data in a way that requires explicit control over keys or when you prefer to treat the data as a collection.
When to Use ViewBag
- ViewBag offers cleaner, more readable syntax using dynamic properties, so it’s ideal when you want quick and simple data passing without needing explicit keys or dictionary operations.
- It is best suited for passing small amounts of simple data (e.g., page titles, messages, flags) where type checking is not critical and you prefer avoiding casting.
- ViewBag is excellent when you want to keep your Controller and View code concise and easy to write and read.
Summary:
ViewBag is a flexible, dynamic way to pass data from Controllers to Views in ASP.NET Core MVC. It is simple to use and ideal for small, temporary data, such as messages, titles, or flags, without requiring strongly typed models.
However, its dynamic nature means you lose compile-time checking and IntelliSense support, increasing the risk of runtime errors due to typos or missing data. For larger, complex, or critical data, strongly typed models remain the recommended approach.
Understanding how and when to use ViewBag effectively can help you write cleaner, more maintainable MVC applications while keeping your views dynamic and responsive.
In the next article, I will discuss Strongly Typed Views in ASP.NET Core MVC Applications with Examples. In this article, I explain ViewBag in the ASP.NET Core MVC application. I hope this article will help you with your needs.
Typo ‘intelligence’ to be corrected as ‘intellisense’
nice
Great