;

Difference Between ViewBag, ViewData and TempData in ASP.NET MVC


Tutorialsrack 18/02/2021 C# ASP.NET MVC

In this article, you will learn what is the difference between ViewBag, ViewData and TempData in ASP.NET MVC. This is one of the most asked interview questions if you are preparing for an ASP.NET Interview Questions. ViewData, ViewBag and TempData are used for passing data and objects in various scenarios.

The following are the scenarios where you can use these objects.

  1. Pass the data from Controller to View.
  2. Pass the data from one action to another action in the same Controller.
  3. Pass the data in between Controllers.
  4. Pass the data between consecutive requests.

ViewBag

  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. 
  • ViewBag is used for passing data from the Controller to the corresponding View.
  • While retrieving the value of ViewBag, there is no need for Type Casting the data.
  • ViewBag is just a wrapper around the ViewData.
  • ViewBag is available only for Current Requests. The value of ViewBag will become null while redirecting.

Example of ViewBag

Example - ViewBag on Controller
Public ActionResult Index()
{
    ViewBag.Title = "Welcome To Tutorialsrack";
    return View();
}
C#

You can call this on the corresponding View like this:

Example - Call ViewBag on the Corresponding View
<h2>@ViewBag.Title</h2>
Markup

ViewData

  • ViewData is a dictionary of objects that are derived from ViewDataDictionary class and is accessible using strings as keys.
  • ViewData is used for passing data from the Controller to the corresponding View.
  • While retrieving the value of ViewData, it requires typecasting for complex data types and also requires null checks for null values to avoid exceptions.
  • ViewData is available only for Current Requests. The value of ViewData will become null while redirecting.

Example of ViewData

Example - ViewData on Controller
Public ActionResult Index()
{
    ViewData["Title"] = "Welcome To Tutorialsrack";
    return View();
}
C#

You can call this on the corresponding View like this:

Example - Call ViewData on the Corresponding View
<h2>@ViewData["Title"]</h2>
Markup

TempData

  • TempData is also a dictionary derived from TempDataDictionary class and stored in short lives sessions and it is a string key and object value.
  • TempData is used to pass the data from one action to another action in the same Controller or different Controllers as well as Controller to View. 
  • While retrieving the value of TempData, it requires typecasting for complex data type and also requires null checks for null values to avoid exceptions.
  • TempData internally uses session variables.
  • TempData is available for Current and Subsequent Requests. It will not be destroyed on redirection. TempData the scope is limited to the next request and if you want TempData to be available even further, you should use Keep() and Peek().

Learn More About Keep() vs Peek()

Example of TempData

Example - TempData
public ActionResult Index()
{
    TempData["Title"] = “Welcome To Tutorialsrack”;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var message= TempData["Title"];
    return View();
}
C#

ViewData vs ViewBag vs TempData

The difference Between ViewData vsViewBag vs TempData are as follows:

ViewData

ViewBag

TempData

It is a Key-Value Dictionary collection

ViewBag is a dynamic property

It is a Key-Value Dictionary collection

ViewData is a dictionary object and it is a property of ControllerBase class

ViewBag is the Dynamic property of the ControllerBase class.

TempData is a dictionary object and it is a property of the ControllerBase class.

ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above

ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above

TempData is also introduced in MVC1.0 and available in MVC 1.0 and above.

ViewData also works with .net framework 3.5 and above

ViewBag only works with .net framework 4.0 and above

TempData also works with .net framework 3.5 and above

Its requires typecasting

ViewBag is a dynamic property, so there is no need for typecasting

Its requires typecasting

Its value becomes null if a redirection has occurred.

Its value also becomes null if a redirection has occurred.

TempData is used to pass data between two consecutive requests.

It is available only for Current Request

is available only for Current Request

TempData only works during the current and subsequent request

I hope this article will help you to understand what is the difference between ViewBag, ViewData, and TempData in ASP.NET MVC.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!



Comments

Recent Posts
Tags
string vs StringBuilder string vs String convert datetime nth highest salary 2nd or 3rd highest salary palindrome C# Programs Extension method Jquery Javascript PHP SQL Server MySQL SQL functions SQL Server Functions MySQL Functions Datetime functions PHP Programs email validation Email validation using jquery and javascript LINQ Programs SQL ALTER Statement SQL DROP Statement SQL SELECT Statement MySQL SHOW Statement C# DateTime C Program Pattern Program Generate random number and strings in C# JSON String in c# DataTable in c# Jquery Attributes Data Conversion Javascript Dates Javascript Date Functions MySQL DateTime Functions C# String String SQL DateTime Functions SQL Server DateTime Functions javascript Functions Jquery Functions Python Programming Python String Python Programs Python Functions Python String Functions String Functions Regular Expression in Javascript Regular Expression in JQuery Regular Expression Validation using Javascript Validation using Jquery Data Validation Resize an Image Bitmap image Graphics Image in C# QueryString in C# QueryString Python Datetime Functions Python Date Formating Date Formatting Globalization CultureInfo System.Globalization Python Programming Examples Python Pattern Programs Python List Python Dictionary C# DataType C# Function C# String Functions Javascript String Functions Javascript Array Functions Custom Date And Time Formatting Standard Date and Time Formatting C# IP Address Python IP Address Computer Networks Computer Networks-IP Addressing Session in C# Session in ASP.NET Session in ASP.NET MVC C# Session Session State WEB API Web API Error JSON Serialization ASP.NET WEB API Error Department Wise Nth Highest Salary Difference Between Jquery Events Javascript Events HTML & CSS CSS Properties Web Design Web Development CSS Styles Regular Expression in C# ASP.NET MVC Routing Custom Routing in ASP.NET MVC Routing in ASP.NET ASP.NET Web.Config ASP.NET MVC Web.Config Web.Config Configuration Java Programs Java Basic Programs Java Programming Examples Java DateTime Java String Control Statements in Java Software Development Tools Development Tools Javascript Object Javascript Operator JavaScript Object Properties JavaScript Object Methods Javascript Errors JQuery Errors Javascript Array Array methods Javascript Array Methods C# Keywords Windows Commands NodeJs Commands Linux Commands macOS Terminal Commands Base64 Encoding and Decoding SQL Server Error SQL Server Index MongoDB DateTime MongoDB Operators MongoDB Aggregation Operators SQL Server Constraints ReactJs Errors ReactJS Error Fixes ReactJs Modules SQL Server Backup SQL Server Variables ASP.NET Core ASP.NET Core Middleware ASP.NET Core Filters