Skip to main content

Posts

Showing posts from July, 2015

ViewData vs ViewBag vs TempData vs Session

In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session. Now question is that when to use ViewData, VieBag, TempData and Session. Each of them has its own importance. In this article, I am trying to explain the differences among these four. ViewData ViewData is a dictionary object that is derived from ViewDataDictionary class. public ViewDataDictionary ViewData { get ; set ; } ViewData is a property of ControllerBase class. ViewData is used to pass data from controller to corresponding view. It’s life lies only during the current request. If redirection occurs then it’s value becomes null. It’s required typecasting for getting data and check for null values to avoid error. ViewBag ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. Basically it is a wrapper arou