Passing Data From Controller To View With ViewData - Part Two

About Article
 
This article will tell you almost everything about passing data from Controller to View in ASP.NET MVC using ViewData. I am writing this article to tell you the basic to advance foremost concepts about ways to pass data from Controller to View. This article is the second one in the series named as “Passing Data from Controller to View”. You’ll learn all the ways in each separate article. Stay tuned!
 
I would strongly recommend reading my previous articles, which will be defining the basic concepts ASP.NET MVC. Articles are listed below:
Especially, read my consecutive previous article in which I have taught the way of passing the data from Controller to View. In the previous article, we passed the Model to the View by passing an argument to a View method. This is the link to the previous article.
 
Read this article, check the code after downloading, and then feel free to give your feedback.
 
The topics to be covered are,
  1. What is ViewData?
  2. Passing the data from Controller to View using ViewData

Introduction and Background

 
As we know Controller is the class whose responsibility is to handle all the HTTP requests and then execute appropriate View. And View gives us the HTML markup that we display to the user. And for displaying anything on the View, there should be some data that is passed from Controller to View. And in this and next articles, you will learn how to pass data from Controller to View.
 
In this article, you’ll learn how to pass strongly typed data from Controller to View using ViewData. And you’ll see other ways to pass data, in coming articles. So stay tuned.
 

What is ViewData?

 
ViewData is a dictionary for the view data having the type of ViewDataDictionary. And it is one of the properties of ControllerBase class so when we create a Controller, then that Controller will automatically inherit the Controller class and this Controller class inherits ControllerBase class. That’s why we can be able to access this ViewData property in each Controller. You can see in the image below the Controller class which inherits the ControllerBase class.
 
Passing data from Controller to View with ViewData
 
And in the ControllerBase class, the ViewData property is defined, see below its syntax.
  1. namespace System.Web.Mvc  
  2. {  
  3.   /// <summary>Represents the base class for all MVC controllers.</summary>  
  4.   public abstract class ControllerBase : IController  
  5.   {  
  6.     //Other code is removed for clarity.  
  7.     /// <summary>Gets or sets the dictionary for view data.</summary>  
  8.     /// <returns>The dictionary for the view data.</returns>  
  9.     public ViewDataDictionary ViewData { get; set; }  
  10.       
  11.   }  
As you can see, ViewData is of type ViewDataDictionary that contains the Key-Value pair where the key must be a string. ViewData is used to pass the data from the Controller to the corresponding View. Importantly, this data can only be passed from Controller to its corresponding View, not in backward direction. You may say it is “short-life” it means when redirection occurs (from View to Controller) then the value of the dictionary becomes null. So it is only valid in the current request. Another important point for ViewData is, it is necessary to do typecasting for complex and strongly typed data it always check null values to avoid errors. Now let’s move towards its example to see its use practically.
 

Passing the strongly typed data from Controller to View using ViewData

 
To pass the strongly-typed data from Controller to View using ViewData, we have to make a model class then populate its properties with some data and then pass that data to ViewData dictionary as Value and selecting Key’s name is the programmer’s choice. And then in the View, we can access the data of model class by using ViewData dictionary with the pre-defined keys. Let’s create a project to take a look at an example.
 
Go to File then New and select “Project” option.
 
Passing data from Controller to View with ViewData
 
Then, create the ASP.NET web application project as depicted below.
 
Passing data from Controller to View with ViewData
 
Then select “Empty” and tick “MVC” then click OK.
 
Passing data from Controller to View with ViewData
 
The project is created successfully.
 
Now, create a class named as “Employee” in the Models folder, shown below.
 
Passing data from Controller to View with ViewData
 
Passing data from Controller to View with ViewData
 
Now, add some properties to this class as the code is given below.
  1. namespace DataCtoV.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public byte EmployeeId { get; set; }  
  6.         public string EmployeeName { get; set; }  
  7.         public string Address { get; set; }  
  8.         public string Phone { get; set; }  
  9.     }  
  10. }  
Now, we’ll add a Controller from where this data of employee will pass. Let’s create a Controller as shown below.
 
Passing data from Controller to View with ViewData
 
Then, select “MVC 5 Controller– Empty” and click Add.
 
Passing data from Controller to View with ViewData
 
Then, give the name of the Controller and click on Add.
 
Passing data from Controller to View with ViewData
 
The Controller is created successfully. In this Controller, we’ll make an action method with the name of “GetEmployeeData” in which we’ll make an object of “Employee” model class and populate this object with some data. Then, pass this object to the ViewData dictionary as Value and give Key named as “EmployeeData”. The code of “EmployeeDataController” is given below.
  1. public class EmployeeDataController : Controller  
  2. {  
  3.     // GET: EmployeeData  
  4.     public ActionResult GetEmployeeData()  
  5.     {  
  6.         List<Employee> emp = new List<Employee>  
  7.         {  
  8.             new Employee  
  9.             {  
  10.                 EmployeeId = 1,  
  11.                 EmployeeName = "John",  
  12.                 Address = "12 Fremont St. Clermont, FL 2813",  
  13.                 Phone = "+1-234-2838421"  
  14.             },  
  15.             new Employee  
  16.             {  
  17.                 EmployeeId = 2,  
  18.                 EmployeeName = "Smith",  
  19.                 Address = "14 Highland Drive Fort Worth, TX 3994",  
  20.                 Phone = "+1-234-2244521"  
  21.             },  
  22.             new Employee  
  23.             {  
  24.                 EmployeeId = 3,  
  25.                 EmployeeName = "Marry",  
  26.                 Address = "23 Fremont Road Milledgeville, GA 6788",  
  27.                 Phone = "+1-234-46568421"  
  28.             }  
  29.         };  
  30.   
  31.     ViewData["EmployeeData"] = emp;  
  32.   
  33.     return View();  
  34.     }  
  35. }  
Because we don’t have any View named as “GetEmployeeData” in the Views folder, so let’s create it. For creating a View, right-click on “GetEmployeeData” method and select “Add View…” option. The following dialogue box will open, click on “Add”.
 
Passing data from Controller to View with ViewData
 
The View is created successfully. Let’s write the code for it.
  1. @using DataCtoV.Models  
  2. @model IEnumerable<DataCtoV.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Employee Data";  
  5. }  
  6.    
  7. <h3>Employee Data</h3>  
  8.    
  9. <table class="table table-condensed table-hover">  
  10.     <thead>  
  11.         <tr>  
  12.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  13.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  16.         </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.         @foreach (var employee in (IEnumerable<Employee>)ViewData["EmployeeData"])  
  20.         {  
  21.             <tr>  
  22.                 <td>@employee.EmployeeName</td>  
  23.                 <td>@employee.EmployeeName</td>  
  24.                 <td>@employee.Address</td>  
  25.                 <td>@employee.Phone</td>  
  26.             </tr>  
  27.         }  
  28.     </tbody>  
  29. </table>  
You can see in the code that we have made a table to represent the strongly typed data of the Employee model class. We have used foreach loop to iterate the data of each employee passed from the Controller.
 
To iterate the data, here, we have used ViewData dictionary which is calling the data from Controller with the help of Key named as “EmployeeData”. And you can also see that we have cast the ViewData to Employee.
 
Note
We must have to cast the ViewData before using it.
 

Why casting?

 
Passing data from Controller to View with ViewData
 
As we know, ViewData has type ViewDataDictionary and this Dictionary has type “object”, and the foreach loop cannot accept variables having type “object”. In the object type, the GetEnumerator method is not defined that’s why we can’t iterate the data of Employee’s collection.
 
To iterate the data of Employee’s collection properly, we have to cast it to IEnumerable, because there a list/collection of Employees is coming and only in IEnumerable, the GetEnumerator is defined for iterating it properly. Hence we must have to cast it in the foreach loop. See the Error below without casting.
 
Passing data from Controller to View with ViewData
 

Ways of Casting ViewData

 
One way of casting the ViewData is described above, which is at a time casting of ViewData in the foreach loop. The code is given below.
 
Passing data from Controller to View with ViewData
 
Another way of casting the ViewData is, cast the ViewData in the Multi-Statement Razor Code block for C#, and then use the variable in the foreach loop. You can see code below:
 
Casting in the code block,
  1. @{  
  2.     ViewBag.Title = "Employee Data";  
  3.     var employeeData = (IEnumerable<Employee>)ViewData["EmployeeData"];  
  4. }  
Then use the “employeeData” variable in the foreach loop, as shown below.
  1. @foreach (var employee in employeeData)  
  2.     {  
  3.         <tr>  
  4.             <td>@employee.EmployeeName</td>  
  5.             <td>@employee.EmployeeName</td>  
  6.             <td>@employee.Address</td>  
  7.             <td>@employee.Phone</td>  
  8.         </tr>  
  9.     }  
All the code of “GetEmployeeData” view is given below for your convenience.
 
GetEmployeeData.cshtml
  1. @using DataCtoV.Models  
  2. @model IEnumerable<DataCtoV.Models.Employee>  
  3. @{  
  4.     ViewBag.Title = "Employee Data";  
  5.     var employeeData = (IEnumerable<Employee>)ViewData["EmployeeData"];  
  6. }  
  7.    
  8. <h3>Employee Data</h3>  
  9.    
  10. <table class="table table-condensed table-hover">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  14.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  15.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  16.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  17.         </tr>  
  18.     </thead>  
  19.     <tbody>  
  20.         @foreach (var employee in employeeData)  
  21.         {  
  22.             <tr>  
  23.                 <td>@employee.EmployeeId</td>  
  24.                 <td>@employee.EmployeeName</td>  
  25.                 <td>@employee.Address</td>  
  26.                 <td>@employee.Phone</td>  
  27.             </tr>  
  28.         }  
  29.     </tbody>  
  30. </table>  
You have seen the reason of casting and ways to do casting. Now simply let’s build and run the application. You should see the following output.
 
Passing data from Controller to View with ViewData
 
Now, you can see the highlighted heading, i.e., EmployeeId and EmployeeName. These heading are not looking good and user-friendly. It is the same as the property name so it is not good for the user. So let’s change it.
 
To change this name we have to apply a data annotation to EmployeeId and EmployeeName property, named as Display and then set its Name property to “Serial No” and “Name” respectively. You can see the changed code of “Employee” model class below,
  1. [Display(Name = "Serial No")]  
  2. public byte EmployeeId { get; set; }  
  3.    
  4. [Display(Name = "Name")]  
  5. public string EmployeeName { get; set; }  
Now, simply build and run the application. Then, you’ll see the following output.
 
Passing data from Controller to View with ViewData
 

Summary

 
In this article, you have learned that how to pass strongly typed data from Controller to View using ViewData dictionary, in which firstly, you should make a model class then populate its properties with some data then pass that object to the ViewData dictionary as Value and pass Key as a string. You have learned it with the help of an example.
 
Conclusion
 
I hope this article has helped you in understanding the concepts about passing strongly typed data from Controller to View using ViewData in ASP.NET MVC. Stay tuned for my next articles because this article is the second one in the series of “Passing data from Controller to View” and you’ll learn more about passing data in coming articles. If you have any query, please feel free to contact me in the comments section. Also, do provide the feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.


Similar Articles