I have often seen entry level developers struggle with the differences between and usage of ViewData, ViewBag and TempData in ASP.NET MVC. And while there are many articles and blog posts on this topic out there, I’ll try to explain it simply.
To start with, ViewData, ViewBag, and TempData all three are objects in ASP.NET MVC that are used to carry or pass data in different scenario. You may have a requirement to pass data in the following cases:
- Pass data from controller to view;
- Pass data from one controller to another controller;
- Pass data from one action to another action;
- Pass data between subsequent HTTP requests
At a higher level, we can depict the use of ViewData, ViewBag, and TempData as shown in the image below:
Passing Data from Controller to View
Let us consider a scenario where you’re passing data from controller to view. Usually we pass complex data to the view using the model. Here let’s say we have a strongly typed View which is using the data model List as shown in the listing below:
Leave a Reply