Working with ViewBag,ViewData and TempData

     In previous chapters we used ViewBag for passing data from controller to view.In addition to ViewBag MVC offers us ViewData and TempData for passing data from controller to view. ViewBag and ViewData are almost similar but in case of  TempData, it performs additional task when compare with both.

     ViewData and ViewBag both are used to pass the data from controller to view.Their values become null when redirection occurs means moving to another action. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using string as keys. Viewdata requires typecasting for complex data.We need to check for null in case of ViewData for avoiding errors.
Whereas ViewBag is a dynamic property and no need of any typecast. 

     Now we will look into how to use ViewBag and ViewData.Create a controlller and change code like below in action method.

public ActionResult Index()
{
    List<string> objlist = new List<string>();
    objlist.Add("MVC");
    objlist.Add("Dot Net");
    objlist.Add("C Sharp");
          
    ViewData["DataPass"] = objlist;
          
    return View();
}

    In above example I took a list of string type and added few string values(MVC,Dotnet,C Sharp) and finally assigned list object to ViewData. Now we are going to collect same in view without casting then our application throws an error as shown in below.

Using ViewData


      Now make the code change like below

@{
    Layout = null;
}

<!DOCTYPE html&gt

<html&gt
<head&gt
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
            @foreach(var item in ViewData["DataPass"] as List<string>)
            {
               <p>@item</p>
            }
    </div>
</body>
</html>

     Here we did casting our ViewData as List of string data.If run the application we will get a output like following.

ViewData output

      Now we will look into ViewBag and just change the controller code like below by replacing ViewData with ViewBag.

public ActionResult Index()
{
    List<string> objlist = new List<string>();
    objlist.Add("MVC");
    objlist.Add("Dot Net");
    objlist.Add("C Sharp");
          
    ViewBag.DataPass = objlist;
          
    return View();
}

      Now we are going to collect same ViewBag data in our view without casting like below.

@{
    Layout = null;
}

<!DOCTYPE html&gt

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
            @foreach(var item in ViewBag.DataPass)
            {
               <p>@item</p>
            }
    </div>
</body>
</html>

     In above we didn't provide any casting,even though it will work because it is of dynamic type as earlier said.If we run the application we will get same output as in the case of ViewData.

TempData:

     In above we discussed about ViewData and ViewBag.Now we we are going to work with TempData is a dictionary is derived from TempDataDictionary class.TempData is stored in short lives session.We should only use it during the current and the subsequent requests only(we will check this in example). In case of ViewBag and ViewData we should used for current request only.
We need to do typecasting for TempData too.

     Now we are going to change the controller code like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FirstMVCApplication.Controllers
{
    public class DataPassingController : Controller
    {
        //
        // GET: /DataPassing/
        public ActionResult Index()
        {
            List<string> objlist = new List<string>();
            objlist.Add("MVC");
            objlist.Add("Dot Net");
            objlist.Add("C Sharp");

            TempData["DataPass"] = objlist;

            return RedirectToAction("Output");
        }

        public ActionResult Output()
        {
            return View(TempData["DataPass"]);
        }
     }
}

    In above code in Index method we created a list and list object is assigned to a TempData and from Index method we are redirecting to the Output method.And again in Output method we are collecting TempData and same is returned to the Output view.Now change the output view like below and clear foreach loop in Index.cshtml page.

@{
    Layout = null;
}

<!DOCTYPE html&gt

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @foreach(var item in TempData["DataPass"] as List<string>)
        {
            <p>@item</p>
        }
    </div>
</body>
</html>

     In above code we used casting for TempData otherwise our application will throw an error.Now run the application and be careful to check URL in browser.If browser shows URL like /DataPass/Output immediatly after running the application then we will get a error like following.

TempData error

TempData view error

          So it is better practice to go to Index.cshtml page and run the application or enter URL in browser like /DataPass/Index or change default action in RouteConfig.cs file by change default controller Name to DataPass and action to Index and run the application then we will get a output like ViewData case.