Passing Data in an MVC Application (ViewBag, ViewData, and TempData)

Introduction

Maintaining the state of a Web application is very important when passing the data between multiple requests. In an ASP.NET application, we use different techniques or ways to pass the data from one page to other. ASP.NET provides Session, ViewState, QueryString, Cross Page Posting, and so forth. Most of the time, developers find difficulties understanding and using ViewData, ViewBag, and TempData in an ASP.NET MVC application. In this article, I will explain ViewData, ViewBag, and TempData with examples, and show you how to pass data in an MVC application in different scenarios.

MVC Application

To explain passing data in an MVC application, I have created an empty ASP.NET MVC application.

Open Visual Studio and choose File Menu, then New and click Project. You will see a New Project dialog window. Choose the ASP.NET Web Application; provide the name of the application and click OK.

Next, you need to choose MVC and click OK.

Add a model class “Employee.cs” with the following properties:

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

namespace MySampleDataInMVC.Models
{
   public class Employee
   {
      public int EmployeeID { get; set; }
      public string EmployeeName { get; set;
      public string Department { get; set; }
   }
}

Next, add one controller, named EmployeeController.cs. We will add code in this controller while explaining ViewData, ViewBag, and TempData.

ViewData

ViewData is a dictionary object, a property of the ControllerBase class. It is derived from ViewDataDictionary and is accessed by a string key. ViewData is used to transfer data from the controller to a view. ViewData can be passed in the form of a key-value pair. Type casting is required when fetching data from ViewData; be sure to check for null values to avoid errors.

To demonstrate ViewData, I have created the following View:

@using MySampleDataInMVC.Models
@{
   ViewBag.Title = "Employee Details";

}

<h2>Employee Details</h2>

<div>
   <h4>Employee</h4>
   <hr />
   <dl class="dl-horizontal">
   @{
      var EmployeeDetail = ViewData["EmployeeDetail"] as Employee;
   }

   </dl>
   <h2> @ViewData["Message"] </h2>
   <br />
   <p>EmployeeID Id : @EmployeeDetail.EmployeeID </p>
   <p>EmployeeID Name : @EmployeeDetail.EmployeeName  </p>
   <p>EmployeeID Department : @EmployeeDetail.Department  </p>
</div>

The following Controller action method passes data to the View:

using MySampleDataInMVC.Models;
using System.Web.Mvc;

namespace PassingDataInMVC.Controllers
{
   public class EmployeeController : Controller
   {
      // GET: Student
      public ActionResult Index()
      {
         Employee model = new Employee()
         {
            EmployeeID = 1,
            EmployeeName = "Tapas Pal",
            Department = "Information Technology"
         };
         ViewData["EmployeeDetail"] = model;
         ViewData["Message"] = "This is to print Employee Details
            using ViewData";
         return View();
      }
   }
}

ViewBag

ViewBag is used to pass data from the controller to the view for a single request. ViewBag is a dynamic type collection. The life of ViewBag persists during the current request. It’s a wrapper around the ViewData and also is used to pass data from the controller to the corresponding view. During the redirection, ViewBag’s value becomes null.  To retrieve ViewBag, data typecasting is not required. Refer to the following ViewBag syntax:

ViewBag.name=value;
ViewContext.ViewBag.name=value;
ViewContext.Controller.ViewBag.name=value;

The following example demonstrates ViewBag by displaying employee information.

View Code

@{
   ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>

<div>
   <h4>Employee</h4>
   <hr />
   <dl class="dl-horizontal">
   @{
      var employeeDetail = ViewBag.EmployeeDetail;
   }

   </dl>
   <h2> @ViewBag.Message </h2>
   <br />

   <p>Employee Id : @employeeDetail.EmployeeID</p>
   <p>Employee Name : @employeeDetail.EmployeeName</p>
   <p>Employee Department : @employeeDetail.Department</p>

</div>

Controller Code

The following Controller action method passes data to the View:

using MySampleDataInMVC.Models;
using System.Web.Mvc;

namespace MySampleDataInMVC.Controllers
{
   public class EmployeeController : Controller
   {
      // GET: Student
      public ActionResult Index()

      {
         Employee model = new Employee()
         {
            EmployeeID = 1,
            EmployeeName = "Tapas Pal",
            Department = "Information Technology"
         };
         ViewBag.EmployeeDetail = model;
         ViewBag.Message = "This is to print Employee Details
            using ViewBag";

         return View();
      }
   }
}

TempData

TempData is a dictionary object. It’s a property of the ControllerBase class derived from the TempDataDictionary class. The TempData syntax is the following:

public TempDataDictionary TempData { get; set; }

By using TempData, you can pass data from one controller to another controller or Action to Action. The following View example explains the TempData usage:

View Code

@using MySampleDataInMVC.Models
@{
   ViewBag.Title = "Employee Details";
}

<h2>Employee Details</h2>

<div>
   <h4>Employee</h4>
   <hr />
   <dl class="dl-horizontal">
      @{
         var EmployeeDetail = TempData["EmployeeDetail"] as
            Employee;
      }

   </dl>
   <h2> @TempData["Message"] </h2>
   <br />
   <p>Employee Id : @EmployeeDetail.EmployeeID</p>
   <p>Employee Name : @EmployeeDetail.EmployeeName</p>
   <p>Employee Department : @EmployeeDetail.Department</p>
</div>

The following Controller code explains passing data to the View:

Controller Code

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

namespace PassingDataInMVC.Controllers
{
   public class EmployeeController : Controller
   {
      // GET: Student
      public ActionResult Index()
      {
         Employee model = new Employee()
         {
            EmployeeID = 1,
            EmployeeName = "Tapas Pal",
            Department = "Information Technology"
         };
         TempData["EmployeeDetail"] = model;
         TempData["Message"] = "This is to print Employee Details
            using TempData";
         return View();
      }
   }
}

Conclusion

It’s important to decide during the design phase in MVC which data passing methodology will be used. Most of the time. developers make a mistake and create session variables to pass data. I hope you liked this article and understood the concept of passing data in an MVC application.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read