Passing Data from the Controller to the View

We have just discussed how to pass the data from the controller to the view using the Model object. While calling the view, we are passing the model data as a parameter. But there are times when you want to pass some temporary data to the view from the
controller. This temporary data may not deserve a model class. In such scenarios, we can use either ViewBag or ViewData.

ViewData is the dictionary and ViewBag is the dynamic representation of the same value.

Let us add the company name and company location property using ViewBag and ViewData, as shown in the following code snippet:


Go to https://goo.gl/oYH7am to access the code.
public IActionResult Employee()
{
//Sample Model - Usually this comes from database
Employee emp1 = new Employee
{
EmployeeId = 1,
Name = "Jon Skeet",
Designation = " Software Architect"
};
ViewBag.Company = "Google Inc";
ViewData["CompanyLocation"] = "United States";
return View(emp1);
}

Make the respective changes in the Employee.cshtml View file as well so that we can display the Company name and CompanyLocation values:


Go to https://goo.gl/KmqUhx to access the code.
<html>
<body>
Employee Name : @Model.Name <br />
Employee Designation: @Model.Designation <br />
Company : @ViewBag.Company <br />
Company Location: @ViewData["CompanyLocation"] <br />
</body>
</html>

Run the application after making the preceding changes:

ViewBag and ViewData represent the same collection, even though the entries in the collection are accessed through different methods. ViewBag values are dynamic values and are executed at runtime, whereas the ViewData is accessed through the dictionary.

To test this, let us make a simple change to our view file:

<html>
<body>
Employee Name : @Model.Name <br />
Employee Designation: @Model.Designation <br />
Company : @ViewData["Company"] <br />
Company Location : @ViewBag.CompanyLocation <br />
</body>
</html>

Even though the Company value was stored using ViewBag in the Controller, we're accessing it using ViewData. The same is the case for the CompanyLocation value. We have stored the value using ViewData in the Controller, but we are accessing the value using ViewBag.

When you run the application after making the preceding changes, you'll see the same result as you have seen before.