ViewData and ViewBag in ASP.NET Core MVC

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.

Understanding ViewData

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.

Using ViewData in the Controller

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();
}
        

Using ViewData in the 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>
        

Hello from ViewData!

The count is: 123

List Items:

Important: Since 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.

Understanding ViewBag

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.

Using ViewBag in the Controller

Adding data to ViewBag is straightforward:


public IActionResult About()
{
    ViewBag.PageTitle = "About Us";
    ViewBag.CurrentDate = DateTime.Now;
    return View();
}
        

Using ViewBag in the View

Accessing ViewBag properties in the view:


<h1>@ViewBag.PageTitle</h1>
<p>Today's date: @ViewBag.CurrentDate.ToString("yyyy-MM-dd")</p>
        

About Us

Today's date:

Performance Note: While ViewBag is convenient, it relies on runtime type checking and can be slightly less performant than ViewData or strongly-typed models.

ViewData vs. ViewBag: Key Differences

When to Use Them

Best Practice: For passing significant amounts of data or complex data structures, always prefer strongly-typed models. They offer better maintainability, readability, and compile-time error checking.

Summary

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.