21
NovViewData vs ViewBag vs TempData vs Session
ViewData vs ViewBag vs TempData vs Session: An Overview
In ASP.NET MVC there are three ways - ViewData, ViewBag, and TempData to pass data from the controller to view and in the next request. Like WebForm, you can also use Session to persist data during a user session. Now the question is when to use ViewData, VieBag, TempData, and Session. Each of them has its importance. In this article, I will try to explain the differences among these four.
Read More: MVC Interview Questions and Answers
1. ViewData
- ViewData is a dictionary object that is derived from the ViewDataDictionary class.
public ViewDataDictionary ViewData { get; set; }
- ViewData is a property of the ControllerBase class.
- ViewData is used to pass data from the controller to the corresponding view.
- Its life lies only during the current request.
- If redirection occurs then its value becomes null.
- It requires typecasting for getting data and checking for null values to avoid errors.
ViewData Example
//Controller Code
public ActionResult Index()
{
List Employee= new List();
Employee.Add("Komal");
Employee.Add("Vishal");
Employee.Add("Rahul");
ViewData["Employee"] = Employee;
return View();
}
//page code
<% foreach (var employee in ViewData["Employee"] as List)
{ %>
<%: employee%>
<% } %>
2. ViewBag
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- It is a wrapper around the ViewData and is also used to pass data from the controller to the corresponding view.
public Object ViewBag { get; }
- ViewBag is a property of the ControllerBase class.
- Its life also lies only during the current request.
- If redirection occurs then its value becomes null.
- It doesn’t require typecasting for getting data.
ViewBag Example
//Controller Code
public ActionResult Index()
{
List Employee= new List();
Employee.Add("Komal");
Employee.Add("Vishal");
Employee.Add("Rahul");
ViewBag.Employee= Employee;
return View();
}
//page code
<% foreach (var student in ViewBag.Employee)
{ %>
<%: employee%>
<% } %>
3. TempData
- TempData is a dictionary object that is derived from the TempDataDictionary class and stored in a short-lived session.
public TempDataDictionary TempData { get; set; }
- TempData is a property of the ControllerBase class.
- TempData is used to pass data from the current request to subsequent requests (which means redirecting from one page to another).
- Its life is very short and lies only till the target view is fully loaded.
- It required typecasting for getting data and checking for null values to avoid errors.
- It is used to store only one-time messages like error messages, and validation messages. To persist data with TempData refer to this article: Persisting Data with TempData
TempData Example
//Controller Code
public ActionResult Index()
{
List Employee= new List();
Employee.Add("Komal");
Employee.Add("Vishal");
Employee.Add("Rahul");
TempData["Employee"] = Employee;
return View();
}
//page code
<% foreach (var employee in TempData["Employee"] as List)
{ %>
<%: student%>
<% } %>
4. Session
- In ASP.NET MVC, Session is a property of the Controller class whose type is HttpSessionStateBase.
public HttpSessionStateBase Session { get; }
- Session is also used to pass data within the ASP.NET MVC application and unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
- The session is valid for all requests, not for a single redirect.
- It also required typecasting for getting data and checking for null values to avoid errors.
Example Of Session
// Populating session
public ActionResult Index()
{
Session["SomeKey"] = "Welcome to ScholarHat";
return RedirectToAction("Error");
}
// Retriving session value
public ActionResult Error()
{
var msg = Session["SomeKey"];
// Do Something
}
ViewData Vs ViewBag Vs TempData Vs Session
ViewData | ViewBag | TempData | Session |
Is a key-value dictionary derived from ViewDataDictionary. | Is a Dynamic property. It is a wrapper around ViewData. | Is a key-value dictionary derived from TempDataDictionary. | Is a key-value dictionary derived from TempDataDictionary. |
Un-typed. So, needs type-casting for complex data. | Type casting is not required. | Un-typed: Needs type-casting for complex data type. | Un-typed: Needs type-casting and null checking. |
Used to pass data between controller and view | Used to pass data between controller and view | Used to pass data between requests. I.e. it helps to pass data from one controller to another controller | Used to store a small amount of data for the duration of the user visiting the website |
The lifespan is only for the current request | The lifespan is only for the current request | Lifespan is for the current and subsequent requests. The lifespan of TempData can be increased beyond the first redirection using TempData.Keep() method | lifespan of a session persists till it is forcefully destroyed by the server or the user |
On redirection, the value in the ViewData becomes Null | On redirection, the value in the ViewData becomes Null | The data stored in TempData persists only during redirection | The data stored in Session persists during any number of redirection |
Does not provide compile-time error-checking | Does not provide compile-time error-checking | Does not provide compile-time error-checking | Does not provide compile-time error-checking |
ViewData is safe to use in the webfarm environment as they are not dependent on session | It is safe to use ViewBag in the webfarm environment as they are not dependent on session | TempData is not reliable in webfarm with a cluster of servers as the TempData uses ASP.NET Session for storage. The workaround is to set Session State Mode to Out-of-Process and make the data stored in the TempData serializable | Sessions are not reliable in web farm as they are stored on the server’s memory. In a webfarm scenario, if a server creates a session and the return request goes to another server in the cluster, then the session will be lost. The workaround is to set Session State Mode to Out-of-Process |
Applications
| Applications
| Applications
| Applications
|
Summary
In this article, I tried to explain the difference between ViewData, ViewBag, and TempData. I hope you will refer to this article for your needs. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article.
Unlock the Next Level of MVC:
FAQs
ViewBag is a dynamic property of the controller that allows passing data from the controller to the view.