What is the difference between ViewData, ViewBag and TempData in MVC.Net?

The ViewData, ViewBag and TempData are the mechanism in Asp.Net MVC which allows data to be passed between controller, view or the next action. The ViewBag and ViewData have same usage and behave very similarly unlike the TempData which has its own functions. Below I have described how they are used in different context.

ViewData

ViewData is a dictionary object which helps the data to be sent from the controller to the view. The data is accessible via a string key and sometimes it requires typecasting for complex data type.

public ActionResult Home()
{
ViewData["Title"] = "I am a software developer";
return View();
}

and in the view you can easily access the data.
@ViewData["Title"]

ViewBag

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0 and does not require type casting for complex objects.

public ActionResult Home()
{
ViewData.Title = "I am a software developer";
return View();
}

and in the view you can easily access the data.
@ViewData.Title

TempData

TempData is also a dictionary object which is stored in session. The object is stored in session with a string key and value. This mechanism pass data from one controller to another and also between one action to another action.

example:

public ActionResult Index()
{
TempData["Message"] = "I am a software developer";
return RedirectToAction("Home");
}

public ActionResult Home()
{
var message = TempData[“Message”];
ViewBag.Message = message;
return View();
}

Advertisements

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