Passing Data From Controller To View With ViewBag - Part Three

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 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 define the basic concepts of 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 happens if ViewData and ViewBag call the same Key’s value?

Introduction and Background

As we know, the Controller is the class that is responsible for handling all the HTTP requests and then executing 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. 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 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 a Key-Value pair in which the Key must be a string. ViewData is the property of the 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 must be cast before use in the View. Let’s move towards its code to see its drawbacks.

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

ViewData["EmployeeData"] = emp;

The code of View in for each loop is,

@foreach (var employee in (IEnumerable<Employee>)ViewData["EmployeeData"])
{
    <tr>
        <td>@employee.EmployeeId</td>
        <td>@employee.EmployeeName</td>
        <td>@employee.Address</td>
        <td>@employee.Phone</td>
    </tr>
}

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

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

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

ViewData["EmployeeData"]

“EmployeeData” is the magic string that we have passed as a 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 fields can be added to 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 the “ControllerBase” class so when we create a controller, that controller will automatically inherit the “Controller” abstract class and this “Controller” class inherits the “ControllerBase” abstract class, that’s why we can access the this ViewBag property in each controller. You can see in the image below the “Controller” class which inherits the “ControllerBase” class.

ControllerBase

And in the “ControllerBase” class, the ViewBag property is defined, see below its syntax.

namespace System.Web.Mvc
{
    /// <summary>
    /// Represents the base class for all MVC controllers.
    /// </summary>
    public abstract class ControllerBase : IController
    {
        // Other code is removed for clarity.
        
        /// <summary>
        /// Gets the dynamic view data dictionary.
        /// </summary>
        /// <returns>The dynamic view data dictionary.</returns>
        public dynamic ViewBag { get; }
    }
}

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 populate its properties with some data and then pass that data to ViewBag with the help of a property. Then in the View, we can access the data of the 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 the “Project” option.

ViewBag

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

ASP.NET web application

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

Empty

The project is created successfully.

Now create a class named “Employee” in the Models folder, shown below,

Employee

Class

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

namespace DataCtoV.Models
{
    public class Employee
    {
        [Display(Name = "Serial No")]
        public byte EmployeeId { get; set; }

        [Display(Name = "Name")]
        public string EmployeeName { get; set; }

        public string Address { get; set; }
        public string Phone { get; set; }
    }
}

Now we’ll add a controller from where this data of employees will pass. Let’s create a Controller as shown below,

Controller

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

MVC 5 Controller

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

Add

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 the “Employee” model class and populate this object with some data. Then pass this object to the ViewBag with the help of a property named “employee”. The code of “EmployeeDataController” is given below,

public class EmployeeDataController : Controller
{
    // GET: EmployeeData
    public ActionResult GetEmployeeData()
    {
        List<Employee> emp = new List<Employee>
        {
            new Employee
            {
                EmployeeId = 1,
                EmployeeName = "John",
                Address = "12 Fremont St. Clermont, FL 2813",
                Phone = "+1-234-2838421"
            },
            new Employee
            {
                EmployeeId = 2,
                EmployeeName = "Smith",
                Address = "14 Highland Drive Fort Worth, TX 3994",
                Phone = "+1-234-2244521"
            },
            new Employee
            {
                EmployeeId = 3,
                EmployeeName = "Marry",
                Address = "23 Fremont Road Milledgeville, GA 6788",
                Phone = "+1-234-46568421"
            }
        };

        ViewBag.employee = emp;

        return View();
    }
}

Because we don’t have any View named “GetEmployeeData” in the Views folder, so let’s create it. For creating View, right-click on the “GetEmployeeData” method and select the “Add View…” option. The following dialogue box will open, click on “Add”,

GetEmployeeData

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

@model IEnumerable<DataCtoV.Models.Employee>

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

<h3>Employee Data</h3>

<table class="table table-condensed table-hover">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(e => e.EmployeeId)</th>
            <th>@Html.DisplayNameFor(e => e.EmployeeName)</th>
            <th>@Html.DisplayNameFor(e => e.Address)</th>
            <th>@Html.DisplayNameFor(e => e.Phone)</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var employee in ViewBag.employee)
        {
            <tr>
                <td>@employee.EmployeeId</td>
                <td>@employee.EmployeeName</td>
                <td>@employee.Address</td>
                <td>@employee.Phone</td>
            </tr>
        }
    </tbody>
</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 a foreach loop to iterate the data of each employee passed from the Controller.

To iterate the data, here we have used ViewBag which calls the data from the Controller with the help of a property named “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,

Output

What happens 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 ViewBag

As ViewBag wraps the ViewData 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 “exam” respectively.

The code is as follows,

ViewData["exm"] = "Shah";
ViewBag.exm = "Zain";

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

<br/>
<strong>Output:</strong>
<br/>
<text>We use both ViewBag and ViewData then the output will be as follows:</text>
<br/>
@ViewBag.exm
<br/>
@ViewData["exm"]

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

Passing Data From Controller

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

Application

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 store their data in Dictionary. The dictionary contains a Key-Value pair where the Key must be a string. When ViewData["exm"] = "Shah"; executes, it creates a 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.

 Key-Value pair

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

ViewBag executes

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

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

Application name

Summary

In this article, you have learned how to pass strongly typed data from Controller to View using ViewBag, in firstly, you should make a model class 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 happens if the magic property of ViewBag and the magic key of ViewData become the 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 queries, please feel free to contact me in the comments section. Also, do provide feedback whether positive or negative. It will help me to make my articles better and increase my enthusiasm to share my knowledge.

Previous Part


Similar Articles