Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
ViewData vs ViewBag vs TempData vs Session

ViewData vs ViewBag vs TempData vs Session

27 Mar 2024
Intermediate
416K Views
10 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with Web API Foundations Course - Free

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

1. ViewData

  1. ViewData is a dictionary object that is derived from the ViewDataDictionary class.
    
    public ViewDataDictionary ViewData { get; set; }
    
  2. ViewData is a property of the ControllerBase class.
  3. ViewData is used to pass data from the controller to the corresponding view.
  4. Its life lies only during the current request.
  5. If redirection occurs then its value becomes null.
  6. 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

  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. 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; }
    
  3. ViewBag is a property of the ControllerBase class.
  4. Its life also lies only during the current request.
  5. If redirection occurs then its value becomes null.
  6. It doesn’t require typecasting for getting data.

ViewBag

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

  1. TempData is a dictionary object that is derived from the TempDataDictionary class and stored in a short-lived session.
    public TempDataDictionary TempData { get; set; }
    
  2. TempData is a property of the ControllerBase class.
  3. TempData is used to pass data from the current request to subsequent requests (which means redirecting from one page to another).
  4. Its life is very short and lies only till the target view is fully loaded.
  5. It required typecasting for getting data and checking for null values to avoid errors.
  6. 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

  1. In ASP.NET MVC, Session is a property of the Controller class whose type is HttpSessionStateBase.
    public HttpSessionStateBase Session { get; }
    
  2. 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).
  3. The session is valid for all requests, not for a single redirect.
  4. 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

ViewDataViewBagTempDataSession
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 viewUsed to pass data between controller and viewUsed to pass data between requests. I.e. it helps to pass data from one controller to another controllerUsed to store a small amount of data for the duration of the user visiting the website
The lifespan is only for the current requestThe lifespan is only for the current requestLifespan is for the current and subsequent requests. The lifespan of TempData can be increased beyond the first redirection using TempData.Keep() methodlifespan of a session persists till it is forcefully destroyed by the server or the user
On redirection, the value in the ViewData becomes NullOn redirection, the value in the ViewData becomes NullThe data stored in TempData persists only during redirectionThe data stored in Session persists during any number of redirection
Does not provide compile-time error-checkingDoes not provide compile-time error-checkingDoes not provide compile-time error-checkingDoes not provide compile-time error-checking
ViewData is safe to use in the webfarm environment as they are not dependent on sessionIt is safe to use ViewBag in the webfarm environment as they are not dependent on sessionTempData 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 serializableSessions 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
  • To pass a list of data to render a drop-down list.
  • To pass a small amount of data to be rendered in the view.
  • Not ideal for complex data involving multiple data sources.
Applications
  • To pass a list of data to render a drop-down list.
  • To pass a small amount of data to be rendered in the view.
  • Not ideal for complex data involving multiple data sources.
Applications
  • Useful for storing one-time messages like error messages and validation messages.
  • Used in scenarios to pass small data from one action to another action or one controller call to another controller call.
Applications
  • To check whether the user is logged in to the website.
  • To store the user’s permission information
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

Both are almost similar and it helps us to transfer the data from controller to view whereas TempData also works during the current and subsequent requests.

 ViewData is faster than ViewBag.

No, you do not need to explicitly typecast TempData values in ASP.NET MVC.

The controller in ASP.NET MVC is responsible for handling incoming requests, processing data, and determining the appropriate response to send back to the client.
ViewBag is a dynamic property of the controller that allows passing data from the controller to the view.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this