Learn ViewBag, ViewData, and TempData with Example

In this chapter, you will learn:
1. What is ViewBag and How to use it in Programming?
2. What is ViewData and How to use it?
3. What is TempData and How to use it?
4. What is ViewDataDictionary and how to use it?

What is ViewBag, ViewData and TempData?

ViewBag, ViewData and TempData are used for passing information from controllers to views. Most of the time, you want to display calculated information using views. In this tutorial, I will explain all these three objects with complete programming example to show you how can you use these objects to pass data from controllers to views.

ViewBag

Fact about ViewBag
  1. ViewBag is used to pass data from controllers to views.
  2. ViewBag has a short life means once it passed value from controllers to views, it becomes null.
  3. ViewBag doesn't require typecasting.

You can create ViewBag like this:
ViewBag.YourName = “Value to be passed”;
And,
You can access this data in View Pages like this:
@ViewBag.YourName
Programming Example of ViewBag

1. Open Visual Studio and Create a New MVC 5 Project. I have opened my existing project CompShop Application.

2. Go to Controllers HomeController.cs

3. Find Index ActionResult and paste the following code.

public ActionResult Index()
        {
            ViewBag.FirstValue = "Hello World";
            ViewBag.SecondValue = "Hello ViewBag";
            ViewBag.ThirdValue = "How are you!";
            return View();
        }

4. Now go to Views Home Index.cshtml and open it. Here, paste the following code in order to access controller data.

@{
    ViewBag.Title = "Computer Shop Management";
}

<div class="jumbotron">
    <h2 style="color:chocolate">Welcome to Computer Shop Management</h2>
</div>

<h4>1. @ViewBag.FirstValue</h4>
<h4>2. @ViewBag.SecondValue</h4>
<h4>3. @ViewBag.ThirdValue</h4>

Output:
View Bag

ViewData

ViewData is also used for sending information from controllers to views.

Some fact about ViewData
  1. It is also used for sending information from controllers to views.
  2. Once it sends information, it becomes null.
  3. ViewData is a Dictionary Object that is derived from ViewDataDictionary.
  4. ViewData uses Key-Value pair for storing and retrieving information.
  5. It requires typecasting for complex data type.

You can create ViewData like this:
ViewData["FirstValue"] = "Hello World";
And,
You can access ViewData information like this:
@ViewData["FirstValue"]
Programming Example:
In HomeController.cs
public ActionResult Index()
        {
            ViewData["FirstValue"] = "Hello World";
            ViewData["SecondValue"] = "Hello ViewData";
            ViewData["ThirdValue"] = "How are you!";
            return View();
        }

In Index.cshtml view pages

@{
    ViewBag.Title = "Computer Shop Management";
}

<div class="jumbotron">
    <h2 style="color:chocolate">Welcome to Computer Shop Management</h2>
</div>

<h4>1. @ViewData["FirstValue"]</h4>
<h4>2. @ViewData["SecondValue"]</h4>
<h4>3. @ViewData["ThirdValue"]</h4>

TempData

TempData is also used for sending data from controllers to view but it is little different from ViewBag and ViewData. TempData is mostly used to transfer value from one controller to another controller. It is most useful when you redirect one page to another page and want to send some information along with it. It has a bigger life than ViewBag and ViewData and you can access TempData value in 2 to 3 HTTP Request.


Let’s understand it with ease

Sometimes, you may want to pass value from controllers to redirected view page. This View Page may belong to another controller. For example:

1. You ask login information on the login page.
2. Validate user input in a controller.
3. If the validation is true then you redirect control to an inner page with some data. This data may be used for display login information.
Some Fact about TempData
  1. TempData internally use Session to store value.
  2. You must check for null before using TempData in order to avoid Runtime Error.
  3. TempData is alive in two subsequent request. It uses TempData.Keep() method for third request.
  4. TempData is also an dictionary object that stores information in key-value pair. It is derived from TempDataDictionary.
Programming Example
In this programming example, there are 3 steps.
Step 1. Created TempData in Index Action Methods.
Step 2. Retrieved it in About Method.
Step 3. Printed it in Contact View Page.

Step 1: Open HomeController.cs and paste code in following action methods.
Index() Action Method
public ActionResult Index()
        {
            TempData["FirstValue"] = "Hello World";
            return View();
        }
About() Action Method
public ActionResult About()
        {
            ViewBag.Message = "This is About Page";           
            if(TempData["FirstValue"] != null)
            {                
                TempData.Keep();
                return RedirectToAction("Contact");
            }            
            return View();
        }
Contact.cshtml page
@{
    ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

@{ 
    string msg1 = null;
    if (TempData["FirstValue"] != null)
    {
        msg1 = TempData["FirstValue"].ToString();
    }
   
    <h4>@msg1</h4>
    }
Output
a. When you Run this program, in index page the TempData[“FirstValue”] will be filled with value.
b. When you click on About link, it will redirect you to Contact page and display the information.
c. When again you click on About link, it will not redirect you contact page and shows you about page.
d. After that, if you click on Contact page, you will not see any information of TempData["FirstValue"].
e. Click several times to Index, About and Contact link and try to examine the result and differences.
Temp Data

Summary

In this chapter, you learned ViewBag, ViewData and TempData with short description and complete programming example. I hope, now you will be able to pass data between view pages using ViewBag, ViewData and TempData. In the next chapter, you will learn Models in MVC 5.

More Articles

 

Share your thought