Skip to main content

Command Palette

Search for a command to run...

"Understanding the Differences Between ViewBag, ViewData, and TempData in ASP.NET MVC"

Published
2 min read

ViewBag, ViewData, and TempData are all mechanisms provided by ASP.NET MVC to share data between controller actions and views.

ViewBag and ViewData are similar in that they both allow you to pass data from the controller to the view, but they differ in their underlying implementation.

ViewBag is a dynamic object that uses C# dynamic features to store and retrieve data. You can set values on the ViewBag object in the controller and then access those values in the view using dot notation. For example, in the controller, you might set a value like this:

ViewBag.Title = "My Page Title";

And then in the view, you could access that value like this:

code<title>@ViewBag.Title</title>

ViewData, on the other hand, uses a dictionary to store and retrieve data. You set values on the ViewData dictionary in the controller, and then you can access those values in the view using the ["key"] syntax. For example, in the controller, you might set a value like this:

 codeViewData["Title"] = "My Page Title";

And then in the view, you could access that value like this:

code<title>@ViewData["Title"]</title>

The TempData dictionary is similar to ViewData, but it is used to pass data between actions during a single user request. When you set a value in TempData in one action, you can retrieve that value in a subsequent action. However, once the request is complete, the TempData values are discarded.

In summary, ViewBag and ViewData are both used to pass data from a controller to a view, but ViewBag is a dynamic object, and ViewData is a dictionary. TempData is used to pass data between actions during a single user request

More from this blog

Untitled Publication

13 posts