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 Asp.net MVC. Though they are very similar in nature, but here we learn about some differencesHere are some variables, we se how differently we can use them
@{ ArrayList alColors = new ArrayList(); alColors.Add("Red"); alColors.Add("Green"); alColors.Add("Yellow"); alColors.Add("White"); } @{ string _courseName="Asp.net MVC"; }
Above two variables we will be storing in three different ways
ViewBag Example
@{ ViewBag.Colors = alColors; ViewBag.CourseName =_courseName; }
public object ViewBag { get; }
ViewData Example
@{ ViewData["Colors"] = alColors; ViewData["CourseName"] =_courseName; }
public ViewDataDictionary ViewData { get; set; }
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; }
public TempDataDictionary TempData { get; set; }
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