Temp Data, View Bag, and View Data in .NET MVC

In the previous article, we created the first MVC application in Visual Studio 2022. In this article, we will learn the mechanism available in ASP.NET MVC for managing and passing data between your controller and views – Temp Data, View Bag, and View Data. Understand their purpose, scope, and best practices for effective implementation.

Previous Chapter: Creating and Building First .NET MVC Application using Visual Studio

Temp Data

Temp Data is a temporary storage mechanism in ASP.NET MVC that persists data across HTTP requests, but only for the current user session.

It is commonly used to pass data when redirecting to a different action, ensuring the data is available in the subsequent request.

public class UserController : Controller
{
    [HttpPost]
    public ActionResult Register(User user)
    {
        if (ModelState.IsValid)
        {
            // Save user to database
            TempData["SuccessMessage"] = "User registration successful!";
            return RedirectToAction("Index", "Home");  
        }
        return View(user);
    }
}

Display TempData message in View:

@if (TempData["SuccessMessage"] != null)
{
    <div class="alert alert-success">@TempData["SuccessMessage"]</div>
}

We use Temp Data only for a short life span. We can use the TempData.Keep() method to persist the TempData beyond the next request.

View Bag

The View Bag is a dynamic container in ASP.NET MVC. It allows you to pass arbitrary data from the controller to the view.

With the View Bag, we can easily add custom properties and access them in the views, without the need for a strongly-typed view model.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var message = "Hello from the controller!";
        ViewBag.Message = message;
        return View();
    }
}

index.cshtml:

<h1>@ViewBag.Message</h1>

View Data

In MVC, View Data is a strongly-typed mechanism for passing data from the controller to the view.

Let’s see this in action:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var message = "Hello from the Controller!";
        ViewData["Message"] = message;

        return View();
    }
}

View:

<h1>@ViewData["Message"]</h1>

ViewData is a dictionary type that stores key-value pairs. It only transfers data one-way, from controller to view. Data is available for only one request.

Temp Data vs View Bag vs View Data

Let’s see the difference among 3 in a tabular format.

View DataView BagTemp Data
DefinitionA dynamic property of the ControllerBase class. We can use it to Pass data from the controller to view.A dynamic property of the ControllerBase class. We can use it to Pass data from controller to view.A dictionary object derived from TempDataDictionary class
ScopeLimited to the current requestLimited to the current request (same as ViewData).Available for the next request. We can persist data using TempData.Keep() method.
BenefitStrongly typedMore convenient syntax (uses dot notation like ViewBag.Message).Ideal for temporary data like success messages.

Conclusion

In this article, we learnt about View Bag, View Data and Temp Data in MVC. What are the uses of these 3 and we also explored the differences among these three.

Next Chapter: Introduction to Routing in .NET MVC

Leave a Comment

RSS
YouTube
YouTube
Instagram