Using TempData, ViewData And ViewBag In ASP.NET MVC 5.0: Part 11

Before reading this article, I highly recommend reading the previous part of the series on ASP.NET:

Before learning how to use ViewData, ViewBag and TempData, we should understand what the differences are among them.

Now let’s understand all of them in detail step by step:

ViewData

ViewData is a Dictionary of objects which is derived from ViewDataDictionary class. View Data is used for passing/storing data from controller to view. ViewData is responsible for only the current request. Its value becomes null when a redirection occurs. This is one of the properties of ControllerBaseClass.ViewData returns Object so we need to typecast for complex data type and check for null values.

Let's understand the concept and usage of ViewData/ViewBag/TempData practically.

Click on FILE, New, then Project.

Project

Expand Templates, click on Visual C# and choose “ASP.NET Web Application”.

Give a name to your project, and hit on “OK” button.

ASP.NET Web Application

In the following screenshot, select MVC template, and click “OK” button.

MVC template

Now, my project ready for use, I’m going to add a model class into project.

Right click on “Model”, select “Add”, and click on to “Class” to add a class.

Class

Select “Class” from the list menu and give a name to your class, here I have given it “Speaker.

Click on the “Add” button.

Add class

I’m going to add five properties such as Name, Twitteraccount, Email, City, and MobNo in my “Speaker” class.
  1. public string Name { getset; }  
  2. public string Twitteraccount { getset; }  
  3. public string Email { getset; }  
  4. public string City { getset; }  
  5. public string MobNo { getset; }  
Here's the screenshot:

properties

Now, I need to add a controller in my project, so just go to the “Controllers” folder, right click on it and add a controller.

Controllers

Choose “MVC 5 Controller-Empty” from the menu.

Click on “Add” button.

MVC 5 Controller

Give the name to your controller, here I have given it “MyController.

Click on “Add” button.

add MyController

Here I have ActionResult Index, here I’m going to define date, time, and details, which Store the current DateTime in ViewData object as well as speaker details and return a View. Write the following code:
  1. using DemoMVCData.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace DemoMVCData.Controllers  
  8. {  
  9.     public class MyController: Controller  
  10.     {  
  11.         // GET: My  
  12.         public ActionResult Index()  
  13.         {  
  14.             ViewData["DateTime"] = DateTime.Now;  
  15.             SpeakerSpeakerdetails = newSpeaker();  
  16.             Speakerdetails.Name = "Nitin Pandit";  
  17.             Speakerdetails.Twitter = "@thinkaboutnitin";  
  18.             Speakerdetails.Email = "nitinpandit.00@gmail.com";  
  19.             Speakerdetails.City = "Lives in Noida";  
  20.             Speakerdetails.MobNo = 8010760780;  
  21.             ViewData["SpeakerDetails"] = Speakerdetails;  
  22.             return View("Index");  
  23.         }  
  24.     }  
  25. }  
Right click near “Speaker,” that is object of the model class and resolve it, after this, a namespace will be added “usingDemoMVCData.Models;” in the controller.

Speaker

Now, I need to add a view, for the view right click near Index() and select “Add View”.

select Add View

It takes “Index” name by default, click on to “Add” button.

add index

Now call the ViewData["DateTime"] object in View using @ symbol, as well as speaker details using @ symbol because we have selected the Razor View Engine. Here I want details of the Speaker in the table format, so here I’m using table and form (Html tags). Here we can store model data into viewdata so that we can retrieve on view.
  1. @{  
  2.    ViewBag.Title = "Index";  
  3. }  
  4. @{  
  5.    DemoMVCData.Models.SpeakerSpeakerdetails =  
  6.    (DemoMVCData.Models.Speaker)ViewData["SpeakerDetails"];  
  7. }  
  8.   
  9. <!DOCTYPEhtml>  
  10. <html>  
  11.     <head>  
  12.         <title>It's Nitin Pandit</title>  
  13.     </head>  
  14.     <body>  
  15.         <h2align="center">ViewData  
  16.         </h2>  
  17.         <form name="f1">  
  18.             <div align="center"border="1">  
  19.                 <p>@ViewData["DateTime"]</p>  
  20.                 <table cellspacing="0"width="600">  
  21.                     <tr>  
  22.                         <td>NAME</td>  
  23.                         <td>TWITTER </td>  
  24.                         <td>EMAIL</td>  
  25.                         <td>CITY</td>  
  26.                         <td>MobNo</td>  
  27.                     </tr>  
  28.                     <tr>  
  29.                         <td>@Speakerdetails.Name</td>  
  30.                         <td>@Speakerdetails.Twitteraccount</td>  
  31.                         <td>@Speakerdetails.Email</td>  
  32.                         <td>@Speakerdetails.City</td>  
  33.                         <td>@Speakerdetails.MobNo</td>  
  34.                     </tr>  
  35.                 </table>  
  36.             </div>  
  37.         </form>  
  38.     </body>  
  39. </html>  
You can follow the below screenshot.

Index

Save your project, press F5 to run your project and call “My” controller in the link address like:

http://localhost:56615/My/

output

Now, I’m going to use ViewBag:

ViewBag

ViewBag is a dynamic property (means dynamic keyword introduced in C# 4.0). ViewBag is similar to ViewData. It is also used for passing data from controller to view. ViewBag is available for current requests only, like ViewData. If redirection occurs its value becomes null. It does not require typecasting for getting complex data types unlike ViewData.

ViewBag is a collection of ViewData. ViewBag syntax is easier than ViewData, no need to write extra [] brackets, It's simple, so now write the following code in your 'Mycontroller'.

Inside HomeController, add another Action Method (named ViewBag). Store the current DateTime in ViewBag.DateTime dynamic object and return a View as well as details of the Speaker.
  1. public ActionResultViewbag()  
  2. {  
  3.     ViewBag.DateTime = DateTime.Now;  
  4.     ViewBag.Name = "Nitin Pandit";  
  5.     ViewBag.Twitteraccount ="@thinkaboutnitin";  
  6.     ViewBag.Email = "nitinpandit.00@gmail.com";  
  7.     ViewBag.City = "Lives in Noida";  
  8.     ViewBag.MobNo = "8010760780";;  
  9.     return View("Viewbag");  
  10. }  
Here is the screenshot,

use ViewBag

Right click near Viewbag(), to add a view().

add another view

By default, it takes a name for it (that’s Viewbag).

Click on to “Add” button.

Click on to Add button

Add the following code in View, access the ViewBag in View 'Viewbag' as in the following code:
  1. @{  
  2.    ViewBag.Title = "Viewbag";  
  3. }  
  4.   
  5.   
  6. <h2 align="center">ViewBag  
  7. </h2>  
  8. <center>  
  9.     <p>@ViewBag.DateTime</p>  
  10.     <p>@ViewBag.Name</p>  
  11.     <p>@ViewBag.Twitteraccount</p>  
  12.     <p>@ViewBag.Email</p>  
  13.     <p>@ViewBag.City</p>  
  14.     <p>@ViewBag.MobNo</p>  
  15. </center>  
Here is the screenshot:

Viewbag

Save your project, and press F5 to run it.

Test your data by running the application, and it will display the message which you passed from Controller to view.

Run

TempData

TempData is also a dictionary derived from TempDataDictionary class. This is a property of ControllerBase class. TempData is passing the data from the current request to the next request (means redirecting from one page to another). TempData transfers the data between controllers or between actions. TempData requires type casting for getting data. It is used to store one time messages and its life is very short.

Inside HomeController, add another Action Method (named it Temdata). Store the current details of the Speaker dynamic object and return a View.

TempData keeps the value for the time of an HTTP Request. Using ReturnToAction("Tempview") we can redirect from one action to another action.

Write the following code in “MyController”:
  1. public ActionResultTempdata()  
  2. {  
  3.     TempData["Name"] =  
  4.         "Nitin Pandit who is part of c# corner";  
  5.     TempData["Twitteraccount"] =  
  6.         "@thinkaboutnitin";  
  7.     TempData["Email"] =  
  8.         "nitinpandit.00@gmail.com";  
  9.     TempData["City"] = "Lives in Noida";  
  10.     return RedirectToAction("Tempview");  
  11. }  
  12. public ActionResultTempview()  
  13. {  
  14.     return View();  
  15. }  
You can see the following screenshot:

MyController

For the view, right click near Tempview(), and select “Add View”.

Add View

Click on to “Add” button to add a view named “Tempview”.

add a view

Access the property using TempData[" "] value in this view.
  1. @{  
  2.    ViewBag.Title = "Tempview";  
  3. }  
  4.   
  5.   
  6. <h2>TempData</h2>  
  7. <p>@TempData["Name"]</p>  
  8. <p>@TempData["Twitteraccount"]</p>  
  9. <p>@TempData["Email"]</p>  
  10. <p>@TempData["City"]</p>  
You can follow the below screenshot:

code

Save your project, and run it by pressing F5 key.

Call “Tempview” view.

Tempview

Thanks for reading this article and stay tuned for future articles where you will learn a lot about ASP.NET MVC 5.0.
 
Read more articles on ASP.NET: