ViewData vs ViewBag vs TempData vs Session

ViewData vs ViewBag vs TempData vs Session

27 Mar 2024
Intermediate
406K Views
10 min read

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 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
  • 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

Q1. What are the differences between ViewData ViewBag TempData and session?

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.

Q2. Which is better ViewBag or ViewData?

 ViewData is faster than ViewBag.

Q3. Do I need to typecast tempdata in ASP NET MVC?

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

Q4. What is the difference between viewbag and controller?

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
Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this