In this article, we will explore how to use ViewBag in an ASP.NET Core 3.0 MVC application to pass data from a controller to a view. ViewBag is a dynamic object that provides a simple way to transfer temporary data without the need for strongly typed models.

What is ViewBag?
- ViewBag is a dynamic wrapper around
ViewData, introduced in ASP.NET MVC. - It allows you to pass data from a controller to a view.
- Being dynamic, it does not require typecasting for complex types.
- However, its scope is limited to the current request, so the data cannot be retained across redirects or multiple requests.
When to Use ViewBag
Use ViewBag when:
- You need to pass simple, one-time data (like a message, title, or user info).
- You do not require strong typing.
- You want a quick and dynamic way to transfer data between the controller and the view.
Avoid using ViewBag for large or complex data models. Use ViewModel or ViewData in such cases.
Step-by-Step Example
Step 1: Create a Controller
We are going add Controller with Name Demo3 with Index action method inside that we are going to declare ViewBag with a string value.
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
public class Demo3Controller : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Hi Message";
return View();
}
}
}
Step 2: Create a View
<h1>Index</h1>
Message:- @ViewBag.Message
Read more :- https://tutexchange.com/quick-view-at-developer-features-of-bugpoint-application/
Read more:- https://learn.microsoft.com/en-us/answers/questions/796983/viewbag-in-asp-net-core