6

I'm using .net mvc 4.0 for my new project. I want to know What is the difference between ViewData, ViewBag and TempData?

I tried searching on net but didn't find any well document material.

swati gupta
  • 83
  • 1
  • 1
  • 3
  • 1
    read this http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications – Anirudha Gupta Feb 03 '15 at 12:52
  • 2
    Searching _What is the difference between ViewData, ViewBag and TempData?_ only gave me 6000 hits! –  Feb 03 '15 at 13:06

1 Answers1

9

From Top 10 ASP.NET MVC Interview Questions,

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e., ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller.

Sumit Chourasia
  • 2,394
  • 7
  • 30
  • 57
  • 3
    Don't you think you should clarify that you copied this from [here](http://www.codeproject.com/Articles/653746/Top-ASP-NET-MVC-Interview-Questions)? There is nothing wrong on referencing other sites but original author should get credit – Claudio Redi Feb 03 '15 at 13:08
  • You are also answering an obvious duplicate. – John Saunders Feb 03 '15 at 13:43
  • Yes, I should Have included the reference too... :) – Sumit Chourasia Feb 03 '15 at 13:55
  • When you copy something from somewhere else, **you must include a link to the original, and quote-format the copied text**, otherwise it looks like plagiarism. –  Oct 08 '15 at 05:12