ViewData, ViewBag, TempData and Session in MVC

viewbag vs viewdata tempdata vs session tempdata vs viewdata tempdata vs viewbag viewbag vs session viewbag in mvc 4 razor examples difference between viewbag viewdata and tempdata in mvc with example tempdata keep and peek in mvc tempdata keep vs peek in mvc viewbag in mvc 4 razor examples tempdata vs session viewbag vs viewdata performance tempdata in mvc view why viewbag is slower than viewdata

ViewBag, ViewData, TempData and Session are the options to send value from controller to view or to other action method/pages. ViewData and ViewBag are very straight forward, they used to send the data from controller to view and done but in case of TempData and Session we can pass values from controller to view and even we can get our value from other pages after redirecting. As we know TempData and Session they both are saved into session but their behavior is a little different, in this article we will explore ViewBag and ViewData a little bit and more on TempData and Session with different examples.

Let's take a very simple example of ViewData to pass the data from controller to view and show in view

 // In controller
 ViewData["item"] = "Some string";
 Or
 ViewData("item", "Some string"); 

 // In view
 <div>@ViewData["item"]</div>

It will render the string on the page, very simple, Can we pass object into ViewData, yes we can, let's try it as well,

create a simple class to test it.

 public class Product
 {
    public int Id { get; set; }
    public string Product { get; set; }
 }

 // In controller add to view data
 ViewData["product"] = new Product { Id = 1, Product = "Computer" };

 // In View 
 @{
    var vdProduct = ViewData["product"] as SessionLess.Controllers.Product;      
    <div>
        View Data Values
        <div>
            @vdProduct.Id : @vdProduct.product 
        </div>
    </div>
 }
 //And here is the output:
  View Data Values
  1 : Computer

ViewData Conclusion:

  1. ViewData is a dictionary type public ViewDataDictionary ViewData { get; set; }
  2. ViewData can be used to pass data from controller to view, one way only
  3. ViewData life lies only during the current request
  4. If passing string into ViewData then no need to typecast
  5. if passing object in ViewData then you need to typecast it but before that you need to check if it is not null
  6. ViewData is a property on ControllerBase, which is the parent of Controller class

ViewBag behaves in very similar to ViewData so no need to take examples but just give the Conclusion

  1. ViewBag internally use dynamic public dynamic ViewBag { get; }
  2. ViewBag can also be used to pass data from controller to view, one way only
  3. ViewBag's life also lies only during the current request
  4. ViewBag's a dynamic type so not necessary to typecast
  5. ViewBag is also a property on ControllerBase, which is the parent of Controller class

TempData

Now time to examine TempData, lets first note it’s feature before applying in code

  1. TempData internally use TempDataDictionary public TempDataDictionary TempData { get; set; }
  2. Once data is saved into TempDataDictionary object
  3. TempData persist in it and can be read from any view or any action in any controller
  4. TempData can only be read once, once read, it becomes null
  5. TempData Saves into session so on expiration of session data loss
  6. This behavior is new from ASP.NET MVC 2 and latter version.
  7. In earlier versions of ASP.NET MVC, the values in TempData was available only until the next request
  8. TempData’s life, until it is read or session expire and can be read from anywhere

Let's try to examine it:

  // Assign value in action View1
  TempData["item"] = "TempData value to show";

  // To render in view
  TempData : @TempData["item"]

Let's try to render the value from two different views, say view1 and view 3

  1. Open View1 : value exits
  2. Open View3: Null

Other scenario:

  1. Remove the code to read TempData value from view1
  2. Open different pages
  3. Finally open the page where you written code to read and you will see value exists

It can be handy in some situation like you want to assign once and read only once, say

  1. It can be used to pass the value for error message and show on the page and done
  2. Store the transaction Id before sending the user to bank site, and once user return match with returned value

As we know now, once temp data is read it will no longer be available, so If we want to keep it after reading it once then we can use Keep pr Peek

@TempData[“MyData”];
TempData.Keep(“MyData”);

First read and then indicate to keep it for further use, but if you want to do the same thing in one line then use Peek like this

var str = TempData.Peek("MyData").ToString();

In this way you can use temp data as many times as you want or you can say in this way it will work like a session.

Session

  1. Session stores data into session
  2. Session is not similar to TempData to access one but you can read as many time as you want
  3. Session never becomes null until or unless session timeout or session expire.
  4. Session is not a good practice to use session very frequently or store big data, it hits performance
  5. List item
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • asp.net
By Ali Adravi On 15 Nov, 14  Viewed: 6,024

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 40,268

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 106,142

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 3,793

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 7,049

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 25,605