Passing Data From Controller To View With ViewBag - Part Three

This article will tell you almost everything about passing data from Controller to View in ASP.NET MVC using ViewBag. 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 third one in the series named as “Passing Data from Controller to View”. You’ll learn all the ways in each separate article.

About Article

This article will tell you almost everything you need to know about passing the data from Controller to View in ASP.NET MVC using ViewBag. I am writing this article to tell you the basic to advanced foremost concepts about ways to pass data from Controller to View. This article is the third one in the series named “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.

Especially, read my consecutive previous articles in which I have taught the way of passing the data from Controller to View using ViewData. 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. Drawbacks of ViewData
  2. What is ViewBag?
  3. Passing the data from Controller to View using ViewBag
  4. What happened if ViewData and ViewBag call the same Key’s value?

Introduction and Background

As we know, Controller is the class that is responsible to handle all the HTTP requests and then to execute the 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 the next articles, you will learn how to pass data from Controller to View.

In this article, you’ll learn how to pass a strongly-typed data from Controller to View using ViewBag. And, you’ll see other ways to pass the data, in coming articles. So, stay tuned!

ViewData and its Drawbacks

As you have seen in my previous article, ViewData is the dictionary containing Key-Value pair in which the Key must be a string. ViewData is the property of ControllerBase class and can be accessible in every Controller. ViewData is used to pass the data from the Controller to the corresponding View, importantly its redirection can’t be possible. ViewData is must be cast before use in the View. Let’s move towards its code to see its drawbacks.

For Controller, code of passing data (the employee object) using ViewData is as follows,

  1. ViewData["EmployeeData"] = emp;  

And the code of View in foreach loop is,

  1. @foreach (var employee in (IEnumerable<Employee>)ViewData["EmployeeData"])  
  2.         {  
  3.             <tr>  
  4.                 <td>@employee.EmployeeId</td>  
  5.                 <td>@employee.EmployeeName</td>  
  6.                 <td>@employee.Address</td>  
  7.                 <td>@employee.Phone</td>  
  8.             </tr>  
  9.         }  

Also following is the code of View for accessing any one property of the model class,

  1. @(((Employee)ViewData["EmployeeData "]). EmployeeName)  

You can notice that, this is not looking nice code. Typecasting and a lot of parenthesis make the code a little bit ugly. Another problem with ViewData is, it magic string that we must passed as Key.

  1. ViewData["EmployeeData"]  

“EmployeeData” is the magic string that we have passed as Key. If we change it in the Controller then we need to remember to change it in the View otherwise we’ll get a null exception. ViewData is the old and first concept used to pass the data in MVC. But to improve this Microsoft has introduced ViewBag which is of dynamic type. Now it’s time to look at ViewBag with an example.

What is ViewBag?

ViewBag is a dynamic property and a wrapper around the ViewData. It is a dynamic object and any number of field can be added into it dynamically. We can pass both strongly and weekly typed data using ViewBag. It doesn’t require any typecasting for complex and strongly typed data.

ViewBag is also one of the properties of “ControllerBase” class so when we create a controller, that controller will automatically inherit the “Controller” abstract class and this “Controller” class inherits “ControllerBase” abstract class, that’s why we can access this ViewBag 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 ViewBag 

And in the “ControllerBase” class, the ViewBag 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.   
  8.     /// <summary>Gets the dynamic view data dictionary.</summary>  
  9.     /// <returns>The dynamic view data dictionary.</returns>  
  10.     public dynamic ViewBag { get; }  
  11.   }  
  12. }  

Now let’s move to look at its example.

Passing the data from Controller to View using ViewBag

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property. 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 ViewBag 

Then create the ASP.NET web application project as depicted below,

Passing Data From Controller To View With ViewBag 

Then select “Empty” and tick “MVC” then click OK.

Passing Data From Controller To View With ViewBag 

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 ViewBag 
 
Passing Data From Controller To View With ViewBag 

Now add some properties into this class as the code is given below,

  1. namespace DataCtoV.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.     [Display(Name = "Serial No")]  
  6.     public byte EmployeeId { get; set; }  
  7.    
  8.     [Display(Name = "Name")]  
  9.     public string EmployeeName { get; set; }  
  10.         public string Address { get; set; }  
  11.         public string Phone { get; set; }  
  12.     }  
  13. }  

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 ViewBag 

Then select “MVC 5 Controller– Empty” then click Add.

Passing Data From Controller To View With ViewBag 

Then give the name of the Controller and click on Add.

Passing Data From Controller To View With ViewBag 

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 ViewBag with the help of property named as “employee”. 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.         ViewBag.employee = 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 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 ViewBag 

The View is created successfully. Let’s write the code for it.

  1. @model IEnumerable<DataCtoV.Models.Employee>  
  2. @{  
  3.     ViewBag.Title = "Employee Data";  
  4. }  
  5.    
  6. <h3>Employee Data</h3>  
  7. <table class="table table-condensed table-hover">  
  8.     <thead>  
  9.         <tr>  
  10.             <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>  
  11.             <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>  
  12.             <th>@Html.DisplayNameFor(e => e.Address)</th>  
  13.             <th>@Html.DisplayNameFor(e => e.Phone)</th>  
  14.         </tr>  
  15.     </thead>  
  16.     <tbody>  
  17.         @foreach (var employee in ViewBag.employee)  
  18.         {  
  19.             <tr>  
  20.                 <td>@employee.EmployeeId</td>  
  21.                 <td>@employee.EmployeeName</td>  
  22.                 <td>@employee.Address</td>  
  23.                 <td>@employee.Phone</td>  
  24.             </tr>  
  25.         }  
  26.     </tbody>  
  27. </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 ViewBag which is calling the data from Controller with the help of property named as “employee”. And you can also see that we don’t have to cast the ViewBag to Employee. Now simply build and run the application then you’ll see the following output,

Passing Data From Controller To View With ViewBag 

What happened if ViewData and ViewBag call the same Key’s value?

It will print the same output for both ViewBag and ViewData. It’ll not throw any exception or error. Now let’s understand its concept. As we know, ViewBag is a wrapper around ViewData as shown below,

Passing Data From Controller To View With ViewBag 

As ViewBag wraps the ViewData so it stores the data into ViewDataDictionary, hence the Key (magic string) of ViewData (ViewData["employee"]) and magic property of ViewBag (ViewBag.employee) are the aliases of each other. Both will print the same output. Let’s move to look at a simple example.

In the “GetEmployeeData” action method of “EmployeeDataController”, I write the following code in which I use both ViewData and ViewBag with the same Key and Property name “exm” respectively.

The code is as follows,
  1. ViewData["exm"] = "Shah";   
  2. ViewBag.exm = "Zain";  

Now in the “GetEmployeeData” View let’s write following code to call both ViewData and ViewBag.

  1. <br/>  
  2. <strong>Output:</strong>  
  3. <br/>  
  4. <text>We use both ViewBag and ViewData then the output will be as follows:</text>  
  5. <br/>  
  6. @ViewBag.exm  
  7. <br/>  
  8. @ViewData["exm"]  

 Now, what should be the output? Will the output be like the following?

Passing Data From Controller To View With ViewBag 

No, if you think this is the output then you are wrong. The output will be as below.

Passing Data From Controller To View With ViewBag 

Why and how has it happened? To know the answer, read the reason below:

The reason for such Output

As we know the ViewBag is a wrapper around ViewData and both stores its data into Dictionary. The dictionary contains a Key-Value pair where the Key must be a string. When ViewData["exm"] = "Shah"; executes, it creates result in the dictionary having Key as “exm” and Value as “Shah”. You can see below in the image when I put a breakpoint on ViewData.

Passing Data From Controller To View With ViewBag 

Now ViewBag executes and stores its data into the dictionary with the name of Key as “exm” and Value as “Zain”. You can see in the below image when I put a breakpoint on ViewBag.

Passing Data From Controller To View With ViewBag 

As you can see the Key of ViewBag is same as the Key of ViewData but the value is changed from “Shah” to “Zain”. Now in the dictionary, there is one Key named as “exm” and one value “Zain” because no more than one values can be sustained for one key; that’s why ViewBag overwrites the ViewData and changed the value form “Shah” to “Zain” to maintain only one value for only one key.

As in the dictionary, there is one key named as “exm” and one value named as “Zain”. Then, both ViewData and ViewBag will print the same output as given below.

Passing Data From Controller To View With ViewBag 

Summary

In this article, you have learned how to pass strongly typed data from Controller to View using ViewBag, in which firstly, you should make a model class then populate its properties with some data then pass that object to the ViewBag as Value and pass magic property (Key) as a string. You have learned that what happened if the magic property of ViewBag and magic key of ViewData becomes same 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 ViewBag in ASP.NET MVC. Stay tuned for my next articles because this article is the third 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.