Passing data from Controller to 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:

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 View file as well so that we can display the Company name and Company location values:

<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:

Passing data from Controller to View

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 run-time, whereas the ViewData is accessed through the dictionary.

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

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

Even though I have stored the Company value using ViewBag in the Controller, I am accessing the same using ViewData. The same is the case for the Company Location 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset