In ASP.NET Core MVC, you often need to pass data from your controller to your view. While strongly typed models are the preferred way to transfer complex data, there are scenarios where you might need to pass smaller amounts of loosely typed data. This is where ViewData and ViewBag come into play.
ViewData is a dictionary-like object (ViewDataDictionary) that allows you to pass data between the controller and the view. It stores data as key-value pairs, where both keys and values are of type object.
To add data to ViewData in your controller action:
public IActionResult Index()
{
ViewData["Message"] = "Hello from ViewData!";
ViewData["Count"] = 123;
ViewData["MyList"] = new List { "apple", "banana", "cherry" };
return View();
}
In your Razor view (.cshtml file), you can access the data stored in ViewData using the square bracket notation:
<h2>@ViewData["Message"]</h2>
<p>The count is: @ViewData["Count"]</p>
<h3>List Items:</h3>
<ul>
@foreach (var item in (List<string>)ViewData["MyList"])
{
<li>@item</li>
}
</ul>
The count is: 123
ViewData stores values as object, you need to explicitly cast them to their original types when retrieving them in the view. Failure to do so can lead to runtime errors.
ViewBag is a dynamic property that provides a more convenient way to pass loosely typed data. It uses the DynamicObject class, allowing you to access properties without explicit casting.
Adding data to ViewBag is straightforward:
public IActionResult About()
{
ViewBag.PageTitle = "About Us";
ViewBag.CurrentDate = DateTime.Now;
return View();
}
Accessing ViewBag properties in the view:
<h1>@ViewBag.PageTitle</h1>
<p>Today's date: @ViewBag.CurrentDate.ToString("yyyy-MM-dd")</p>
Today's date:
ViewBag is convenient, it relies on runtime type checking and can be slightly less performant than ViewData or strongly-typed models.
ViewData is a dictionary, requiring explicit casting. ViewBag is dynamic, avoiding explicit casting but losing compile-time type checking.ViewData["Key"] vs. ViewBag.Property.ViewBag is actually implemented using ViewData internally, through a dynamic wrapper.ViewData and ViewBag are useful tools for passing loosely typed data from a controller to a view in ASP.NET Core MVC. ViewData uses a dictionary approach requiring casting, while ViewBag offers a more convenient dynamic syntax. Choose the one that best suits your needs, keeping in mind the trade-offs in type safety and performance.