ViewData vs ViewBag vs TempData in ASP.NET MVC: Differences, When to Use Each, and Implementation Examples

Comments 0

Share to social media

ASP.NET MVC provides three mechanisms for passing data from a controller to a view: ViewData, ViewBag, and TempData. Understanding when to use each is a core MVC skill. This article walks through each mechanism with code examples and a side-by-side comparison.

ViewBag, ViewData, and TempData all are Dictionary objects in ASP.NET MVC and these are used for data passing in various situations.

The following are the situations where we can use TempData and other objects.

  1. Pass the data from Controller to View.

  2. Pass the data from an action to another action in Controller.

  3. Pass the data in between Controllers.

  4. Pass the data between consecutive requests.

What is Dictionary Object?

In C#, Dictionary is used to store the key-value pairs. The Dictionary is the same as the non-generic hashtable. It can be defined under System.Collection.Generic namespace. It has a dynamic nature which means the size of the dictionary grows according to the need.

Here is an example:

What is ViewData?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally.

ViewData contains key-value pairs which means each key must be a string in a dictionary.

The only limitation of ViewData is, it can transfer data from controller to view. It can not transfer in any other way and it is valid only during the current request.

Syntax:

When we want to use the key-value pair to ViewData,

We can also use ViewData in the razor view from controller. Here is the syntax for that:

When we want to add custom objects, array, list, etc, in ViewData, and cast them back in the View. We can use the code snippet as below:

Figure 1: ViewData Flow

Here is an example of ViewData which shows how to transfer data from controller to view using ViewData.

In this example, ViewData[“employees”] is assigned to an employeeList where “employees” is a key and employeeList is a value.

To access the ViewData[“employees”] in the view, here is the snippet of code you can use.

In simple terms, these are the ways to store and retrieve data to and for respectively ViewData as shown:

Storing :

Retriving :

 

In MVC, ViewData does not check compile-time errors. If we misspell the key names, we would not get any errors but we can identify them at the run time.

For example,

Controller:

View

Figure 2: Output

Simple Talk is brought to you by Redgate Software

Take control of your databases with the trusted Database DevOps solutions provider. Automate with confidence, scale securely, and unlock growth through AI.
Discover how Redgate can help you

What is ViewBag?

ViewBag is an object which is dynamically passing the data from Controller to View and this will pass the data as the property of object ViewBag. We do not need to typecast to read the data for null checking here.

Controller:

View:

Here is an example:

Controller:

View:

ASP View bag 2

Figure 3: Output

What is TempData?

TempData is a dictionary object derived from TempDataDictionary which contains key-pair values. It is useful when we want to transfer the data from the Controller to the View in ASP.NET MVC Application. It stays for a subsequent HTTP request as opposed to other options we discussed prior who stay only for the current request.

Although it removes the key-value pair once it is accessed, we can keep it using

Here is an example:

Controller:

View:

Differences between ViewData, ViewBag and TempData:

ViewData

ViewBag

TempData

Key-Value Dictionary Object

Type Object

Key-Value Dictionary Collection

A property of ControllerBase class

A Dynamic property of ControllerBase class

A property of the controllerBase class

Faster

Slower

–

Introduced in MVC 1.0, Available in MVC 1.0 and above

Introduced in MVC 3.0,

Available in MVC 3.0 and above

Introduced in MVC 1.0,

Available in MVC 1.0 and above.

Works with .NET Framework 3.5 and above

Works with .NET framework 4.0 and above

Works with .NET framework 3.5 and above

Type Conversion code is required

Type Conversion code is not required

Type Conversion code is required

Value becomes null if a redirection has occurred

Value becomes null if a redirection has occurred

TempData is used to pass data between two consecutive requests

Lies only during the current request

Lies only during the current request

Only works during the current and subsequent request

Conclusion

Figure 4: Summary

To conclude, it is clear that ViewData is used to pass the data from Controller action to View. Here, we discussed ViewData properties and how to use that in any MVC application.

Stop proving compliance by hand

Redgate Monitor Enterprise checks your SQL Server configuration against the Center for Internet Security (CIS) Benchmarks®, using server- and database-level templates.
Try the demo

 

FAQs

1. What is the difference between ViewData and ViewBag in ASP.NET MVC?

ViewData and ViewBag are the same underlying storage – a ViewDataDictionary keyed by string, valued by object – with two different access syntaxes. ViewData uses dictionary syntax: ViewData[‘UserName’] = ‘Alice’ in the controller, @ViewData[‘UserName’] in the view, requiring a cast if you need typed access like (string)ViewData[‘UserName’]. ViewBag uses dynamic-property syntax (via C#’s dynamic type): ViewBag.UserName = ‘Alice’ in the controller, @ViewBag.UserName in the view, no cast needed. They’re interchangeable – ViewData[‘X’] and ViewBag.X access the same value. Choose based on preference: ViewBag’s dynamic syntax is cleaner for reads but provides no compile-time checking (a typo in @ViewBag.UsreName fails silently as null rather than a compile error). ViewData’s dictionary access is more explicit but more verbose. Both have the same lifetime (current request only) and the same fundamental limitations – modern ASP.NET MVC best practice is strongly-typed view models for primary page data; ViewData/ViewBag for ancillary data only.

2. What is TempData and when should I use it?

TempData is a dictionary-like object (TempDataDictionary) designed for scenarios where data must survive a redirect. Typical example: a controller action processes a form submission and succeeds, then redirects the browser to a confirmation page – the confirmation message needs to be displayed on the confirmation page, but after the redirect the original controller action’s ViewData and ViewBag are gone (different request). TempData stores values for exactly one additional request cycle: TempData[‘Message’] = ‘Saved successfully’; return RedirectToAction(‘Index’);. The redirected-to action can read @TempData[‘Message’]; after that read, the value is marked for removal. Backed by session state by default (or cookies in newer configurations), so TempData adds session dependency. Use TempData for: post-redirect flash messages (success confirmations, error notices), short-lived data crossing a redirect boundary. Don’t use TempData for: data that should persist longer than one request cycle (use session directly), primary page data (use view models), data that doesn’t cross a redirect (use ViewData/ViewBag).

3. Should I use ViewData or a view model in ASP.NET MVC?

Modern ASP.NET MVC best practice: view models for primary page data, ViewData/ViewBag for ancillary supporting data only. Rationale: strongly-typed view models provide compile-time checking (typos in property names are errors, not runtime nulls), IntelliSense in the view template, easier refactoring (rename a property, see all usages update), and clearer contracts between controller and view. Pattern: define a view model class (class UserProfileViewModel { public string UserName {get; set;} public int Age {get; set;} public List<Order> RecentOrders {get; set;} }), populate it in the controller, pass to the view via return View(model), and access strongly-typed properties in the view (@Model.UserName). Use ViewData/ViewBag sparingly for: page title, breadcrumbs, layout-only data that’s not part of the view’s primary responsibility, flash messages from TempData. The general rule: if the view’s template repeatedly references the same data, that data belongs in a view model; if the data is cross-cutting layout concerns, ViewData/ViewBag is appropriate. Razor Pages (newer) has stronger guidance toward PageModel (its equivalent of view model) as the primary pattern; ViewData/ViewBag usage continues to decline in modern ASP.NET Core applications.

This document contains proprietary information and is protected by copyright law.

Copyright © 2026 Red Gate Software Limited. All rights reserved

About the author

Vinod Satapara

See Profile

Vinod is the Technical Director, iFour Technolab Pvt. Ltd. Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

Vinod's contributions

  • Articles

    2

  • Books

    0

  • Top topics