What is the difference between TempData, ViewData, and ViewBag?
Ask by ICSM Computer
Updated 12 Jun 2025
In ASP.NET MVC,
TempData,ViewData, andViewBagare used to pass data from controllers to views, but they differ in lifetime, usage, and behavior.Quick Comparison Table
ViewDataViewBagTempDataDictionary<string, object>ViewData)TempDataDictionary(stringkeys)ViewData, more conciseViewData["Name"]ViewBag.NameTempData["Name"]Detailed Breakdown
ViewDataViewDataDictionary)ViewBagViewDatausing dynamicTempDataRedirectToAction)Session— so session must be enabledWhen to Use What?
ViewBagorViewDataViewBagorViewDataTempDataTempDataViewModelinsteadTip: Reuse ViewBag/ViewData with Partial Views
Both
ViewBagandViewDataare passed automatically to partial views:Pitfalls
TempData.Keep().