Displaying Data On View From Controller

This article introduces various approaches to show dynamic data on a view.

Introduction

This article introduces various approaches to show dynamic data on a view. ASP.NET MVC offers two ways to communicate data across model-view-controller boundaries, ViewData and TempData. These objects are dictionaries available as properties in both controllers and views. Thus, passing data from a controller to a view can be as simple as setting a value in the controller. You will go through five approaches in this article for passing data from a controller to a view. These approaches are,

  • ViewData Object
  • ViewData Model
  • ViewBag Object
  • TempData Object
  • Strongly Typed Views

ViewData Object

The ControllerBase class has a ViewData dictionary property that can be used to populate data on controller and view. ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar "key/value" syntax, in other words it is a dictionary of objects that are accessible using strings as keys. The ViewData used to pass data from a controller to a corresponding view and it's life exists only during the current request. We will write code to understand the ViewData object.

Create a Student class so we can pass a Student class object to the view from the controller using ViewData.

  1. namespace DisplayDataExample.Code {  
  2.     public class Student {  
  3.         public string Name {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public int Age {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string City {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  
Create a controller "DisplayDataController" class ("DisplayDataController.cs"). After that create an action method in this controller where ViewData stores the Student object and will be passed on the view.
  1. public ActionResult Index() {  
  2.     var student = new Student() {  
  3.         Name = "Sandeep Singh Shekhawat",  
  4.             Age = 24,  
  5.             City = "Jaipur"  
  6.     };  
  7.     ViewData["Student"] = student;  
  8.     return View();  
  9. }  
Create a view that shows the ViewData to the user in the UI. ViewData will be accessed in the razor code block and storeed in the Student type variable, then we can retrieve data from this student variable.

The following snippet is from "Index.cshtml":

  1. @using DisplayDataExample.Code  
  2. @{  
  3.    var student = ViewData["Student"] as Student;   
  4. }  
  5. <table>  
  6.    <tr>  
  7.       <th>Name</th>  
  8.       <th>Age</th>  
  9.       <th>City</th>  
  10.    </tr>  
  11.    <tr>  
  12.       <td>@student.Name</td>  
  13.       <td>@student.Age</td>  
  14.       <td>@student.City</td>  
  15.    </tr>  
  16. </table>  
Notice that when we go to use our object on the view, we need to cast it since the ViewData is storing everything as an object.

ViewData Model

The ViewData object offers a Model property, that represents the primary object that is the target of the request. The ViewDate Model is used when you want to pass strongly-typed data from a controller to a view. We use the previous Student class and will be passed a Student class object to the View from the controller, so we create an action method "StudentInformation()" in the "DisplayDataController" controller.
  1. public ActionResult StudentInformation() {  
  2.     var student = new Student() {  
  3.         Name = "Sandeep Singh Shekhawat",  
  4.             Age = 24,  
  5.             City = "Jaipur"  
  6.     };  
  7.     return View(student);  
  8. }  
Thereafter create a view ("StudentInformation.cshtml") that shows the data of the student object data. ViewData has a Model property that has this object when it is passed from the controller so you can get the Student object from "ViewData.Model". The Action Method passes a strongly typed object so you don't need to cast it. The "StudentInformation" view snippet is from "StudentInformation.cshtml".
  1. @using DisplayDataExample.Code;  
  2. @{  
  3.    var student = ViewData.Model;   
  4. }  
  5. <table>  
  6.    <tr>  
  7.       <th>Name</th>  
  8.       <th>Age</th>  
  9.       <th>City</th>  
  10.    </tr>  
  11.    <tr>  
  12.       <td>@student.Name</td>  
  13.       <td>@student.Age</td>  
  14.       <td>@student.City</td>  
  15.    </tr>  
  16. </table> 
ViewBag Object

ViewBag is dynamic property that takes advantage of new dynamic features in C# 4.0. It's also used to pass data from a controller to a view. In short, The ViewBag property is simply a wrapper around the ViewData that exposes the ViewData dictionary as a dynamic object. Now create an action method "StudentSummary" in the "DisplayDataController" controller that stores a Student class object in ViewBag.
  1. public ActionResult StudentSummary() {  
  2.     var student = new Student() {  
  3.         Name = "Sandeep Singh Shekhawat",  
  4.             Age = 24,  
  5.             City = "Jaipur"  
  6.     };  
  7.     ViewBag.Student = student;  
  8.     return View();  
  9. }  
Thereafter create a view StudentSummary ("StudentSummary.cshtml") that shows student object data. ViewBag does not require typecasting for complex data type so you can directly access the data from ViewBag.
  1. @{  
  2. ViewBag.Title = "Student Summary";  
  3.    var student = ViewBag.Student;  
  4. }   
  5. <table>  
  6.    <tr>  
  7.       <th>Name</th>  
  8.       <th>Age</th>  
  9.       <th>City</th>  
  10.    </tr>  
  11.    <tr>  
  12.       <td>@student.Name</td>  
  13.       <td>@student.Age</td>  
  14.       <td>@student.City</td>  
  15.    </tr>  
  16. </table>  
Here we used one more thing, "ViewBag.Title", that shows the title of the page.

TempData Object

TempData is a dictionary object derived from the TempDataDictionary class and stored in short-lived sessions. TempData is used to pass data from a current request to a subsequent request. Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. Therefore, the only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view. TempData also requires typecasting for a complex data type.

Create two action methods, one is "StudentDetail()" and another is "Student()" under the DisplayDataController controller. TempData initializes a Student class object in the StudentDetail() action method then redirect the request to the Student() action method then the Student() action method renders a view on the UI. So here are two requests; create one request for the StudentDetail() action and another subsequent request for the Student() action. TempData is initialized in the parent request but it isn't destroyed in subsequent requests.
  1. public ActionResult StudentDeatil() {  
  2.     var student = new Student() {  
  3.         Name = "Sandeep Singh Shekhawat",  
  4.             Age = 24,  
  5.             City = "Jaipur"  
  6.     };  
  7.     TempData["Student"] = student;  
  8.     return new RedirectResult("Student");  
  9. }  
  10. public ActionResult Student() {  
  11.     return View();  
  12. }  
Now create a View ("Student.cshtml") that is rendered by the Student() action method in the controller and you can access TempData on the View that is initialized in a previous request. This snippet is from Student.cshtml:
  1. @using DisplayDataExample.Code  
  2. @{  
  3.    var student = TempData["Student"] as Student;   
  4. }  
  5. <table>  
  6.    <tr>  
  7.       <th>Name</th>  
  8.       <th>Age</th>  
  9.       <th>City</th>  
  10.    </tr>  
  11.    <tr>  
  12.       <td>@student.Name</td>  
  13.       <td>@student.Age</td>  
  14.       <td>@student.City</td>  
  15.    </tr>  
  16. </table>  
Strongly Typed Views

By default, the Model property available within Razor views is dynamic, which means that you are able to access its values without the need to know its exact type. Razor makes this pretty easy; use the @model keyword to indicate the model's type name.

Create a model Teacher ("Teacher.cs") that is a C# class that has properties under the Models folder.
  1. namespace DisplayDataExample.Models {  
  2.     public class Teacher {  
  3.         public string Name {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string Subject {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string Department {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  

Now create an action method "TeacherInformation()" under the DisplayDataController controller that renders a view with the model. This action method passes a Teacher class object to the view.

  1. public ActionResult TeacherInformation() {  
  2.     var model = new Teacher() {  
  3.         Name = "ss_shekhawat",  
  4.             Subject = "Quantum Physics",  
  5.             Department = "Physics"  
  6.     };  
  7.     return View(model);  
  8. }  

Then create a view bound to the model. This snippet is from "TeacherInformation.cshtml".

  1. @model DisplayDataExample.Models.Teacher  
  2. @{  
  3. ViewBag.Title = "Teacher Information";  
  4. }  
  5. <table>  
  6. <tr>  
  7.    <th>Name</th>  
  8.    <th>Subject</th>  
  9.    <th>Department</th>  
  10. </tr>  
  11.    <tr>  
  12.       <td>@Model.Name</td>  
  13.       <td>@Model.Subject</td>  
  14.       <td>@Model.Department</td>  
  15.    </tr>  
  16. </table> 
The source code used in this article is available in the zip folder so you can download it and use it.