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.
Expand
Templates, click on
Visual C# and choose “
ASP.NET Web Application”.
Give a name to your project, and hit on “
OK” button.
In the following screenshot, select
MVC template, and click “
OK” button.
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.
Select “
Class” from the list menu and give a name to your class, here I have given it “
Speaker.”
Click on the “
Add” button.
I’m going to add five properties such as Name, Twitteraccount, Email, City, and MobNo in my “
Speaker” class.
- public string Name { get; set; }
- public string Twitteraccount { get; set; }
- public string Email { get; set; }
- public string City { get; set; }
- public string MobNo { get; set; }
Here's the screenshot:
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.
Choose “
MVC 5 Controller-Empty” from the menu.
Click on “
Add” button.
Give the name to your controller, here I have given it “
MyController.”
Click on “
Add” button.
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:
- using DemoMVCData.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace DemoMVCData.Controllers
- {
- public class MyController: Controller
- {
-
- public ActionResult Index()
- {
- ViewData["DateTime"] = DateTime.Now;
- SpeakerSpeakerdetails = newSpeaker();
- Speakerdetails.Name = "Nitin Pandit";
- Speakerdetails.Twitter = "@thinkaboutnitin";
- Speakerdetails.Email = "[email protected]";
- Speakerdetails.City = "Lives in Noida";
- Speakerdetails.MobNo = 8010760780;
- ViewData["SpeakerDetails"] = Speakerdetails;
- return View("Index");
- }
- }
- }
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.
Now, I need to add a view, for the view right click near
Index() and select “
Add View”.
It takes “
Index” name by default, click on to “
Add” button.
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.
- @{
- ViewBag.Title = "Index";
- }
- @{
- DemoMVCData.Models.SpeakerSpeakerdetails =
- (DemoMVCData.Models.Speaker)ViewData["SpeakerDetails"];
- }
-
- <!DOCTYPEhtml>
- <html>
- <head>
- <title>It's Nitin Pandit</title>
- </head>
- <body>
- <h2align="center">ViewData
- </h2>
- <form name="f1">
- <div align="center"border="1">
- <p>@ViewData["DateTime"]</p>
- <table cellspacing="0"width="600">
- <tr>
- <td>NAME</td>
- <td>TWITTER </td>
- <td>EMAIL</td>
- <td>CITY</td>
- <td>MobNo</td>
- </tr>
- <tr>
- <td>@Speakerdetails.Name</td>
- <td>@Speakerdetails.Twitteraccount</td>
- <td>@Speakerdetails.Email</td>
- <td>@Speakerdetails.City</td>
- <td>@Speakerdetails.MobNo</td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
You can follow the below screenshot.
Save your project, press F5 to run your project and call “My” controller in the link address like:
http://localhost:56615/My/
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.
- public ActionResultViewbag()
- {
- ViewBag.DateTime = DateTime.Now;
- ViewBag.Name = "Nitin Pandit";
- ViewBag.Twitteraccount ="@thinkaboutnitin";
- ViewBag.Email = "[email protected]";
- ViewBag.City = "Lives in Noida";
- ViewBag.MobNo = "8010760780";;
- return View("Viewbag");
- }
Here is the screenshot,
Right click near Viewbag(), to add a view().
By default, it takes a name for it (that’s Viewbag).
Click on to “
Add” button.
Add the following code in View, access the ViewBag in View '
Viewbag' as in the following code:
- @{
- ViewBag.Title = "Viewbag";
- }
-
-
- <h2 align="center">ViewBag
- </h2>
- <center>
- <p>@ViewBag.DateTime</p>
- <p>@ViewBag.Name</p>
- <p>@ViewBag.Twitteraccount</p>
- <p>@ViewBag.Email</p>
- <p>@ViewBag.City</p>
- <p>@ViewBag.MobNo</p>
- </center>
Here is the screenshot:
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.
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”:
- public ActionResultTempdata()
- {
- TempData["Name"] =
- "Nitin Pandit who is part of c# corner";
- TempData["Twitteraccount"] =
- "@thinkaboutnitin";
- TempData["Email"] =
- "[email protected]";
- TempData["City"] = "Lives in Noida";
- return RedirectToAction("Tempview");
- }
- public ActionResultTempview()
- {
- return View();
- }
You can see the following screenshot:
For the view, right click near
Tempview(), and select “
Add View”.
Click on to “
Add” button to add a view named “
Tempview”.
Access the property using
TempData[" "] value in this view.
- @{
- ViewBag.Title = "Tempview";
- }
-
-
- <h2>TempData</h2>
- <p>@TempData["Name"]</p>
- <p>@TempData["Twitteraccount"]</p>
- <p>@TempData["Email"]</p>
- <p>@TempData["City"]</p>
You can follow the below screenshot:
Save your project, and run it by pressing F5 key.
Call “
Tempview” view.
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: