In ASP.NET MVC there are three ways - ViewData, ViewBag, and TempData - to pass data from the controller to view 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 their own importance. In this article, I am trying to explain the differences among these four.
ViewData
ViewData
- ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object i.e., Keys and Values where Keys are String while Values will be objects.
- Data is stored as Object in ViewData.
- While retrieving the data it needs to be Type Cast to its original type as the data is stored as the object and it also requires NULL checks while retrieving.
- ViewData is used for passing value from Controller to View.
- ViewData is available only for Current Request. It will be destroyed on redirection.
Example
In the below example, a string value is set in the ViewData object in Controller and it is then displayed in View.
Controller
In the below example, a string value is set in the ViewData object in Controller and it is then displayed in View.
Controller
- public class FirstController: Controller {
- // GET: First
- public ActionResult Index() {
- ViewData["Message"] = "Hello RAJESH!";
- return View();
- }
- }
View
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div> @ViewData["Message"] </div>
- </body>
- </html>
ViewBag
- ViewBag is a Wrapper built around ViewData.
- ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features.
- While retrieving, there is no need for Type Casting data.
- ViewBag is used for passing value from Controller to View.
- ViewBag is available only for Current Request. It will be destroyed on redirection.
Example
In the below example, a string value is set in the ViewBag object in Controller and it is then displayed in View.
Controller
In the below example, a string value is set in the ViewBag object in Controller and it is then displayed in View.
Controller
- public class FirstController: Controller {
- // GET: First
- public ActionResult Index() {
- ViewBag.Message = "Hello RAJESH!";
- return View();
- }
- }


prady kalwaniPosted Jan 22, 2021, 1:16 PM
Really nice explanation. Thank you so much for this article.
IMAD AYOUBPosted Nov 27, 2020, 10:28 AM
Excellent article. Thanks a lot.
Ar VhinPosted May 2, 2018, 10:31 PM
Wow , so helpful and useful blog