ViewBag vs Tempdata vs ViewData

Learn the difference among ViewBag vs Tempdata vs ViewData.

Here we look at what are the difference among ViewBag vs ViewData vs Tempdata in Asp.Net MVC

In earlier articles you have learned about ViewData , TempData and ViewBag in MVC. Though they are very similar in nature, but here we learn about some differences
ViewBag, ViewData and Tempdata Difference

Here are some variables, we se how differently we can use them

    ArrayList alColors = new ArrayList();
    string _courseName=" MVC";

Above two variables we will be storing in three different ways

ViewBag Example

    ViewBag.Colors = alColors;
    ViewBag.CourseName =_courseName;
It is a type object
public object ViewBag { get; }
Works only during the current request

ViewData Example

    ViewData["Colors"] = alColors;                             
    ViewData["CourseName"] =_courseName;
It is Key-Value Dictionary collection
public ViewDataDictionary ViewData { get; set; }
Works only during the current request
Difference between ViewBag and ViewData

ViewBag is a dynamic property, when ViewData is a dictionary object, use key value concept to store and retrieve value, in case of ViewBag we need to remember the name of dynamic property.

ViewBag is slower than ViewData.

Now let's understand TempData Example

    TempData["Colors"]  = alColors;                            
    TempData["CourseName"] =_courseName;
It is Key-Value Dictionary collection
public TempDataDictionary TempData { get; set; }
TempData works during the current and subsequent request
Difference between ViewData and TempData

Like ViewData, TempData is also dictionary object, the difference is we can access the value stored in TempData in next redirected page only once, when we cannot access ViewData value from outside the current page.

You should also read

ViewBag vs ViewData vs Tempdata in MVC
Aspnet MVC Training MVC tutorials, learn model view controllers with c#, develop database driven web application using MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Core Tutorial