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:

image

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:

Read the full article on the Infragistics blog

Advertisements

One thought on “What are ViewData, ViewBag, and TempData in ASP.NET MVC?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s