Using Viewbag In ASP.NET MVC 5

We can use Viewbag just as Viewdata to store Model data and passed to view. But the difference is Viewdata is dictionary object which allow string as keys and typecasting is required while Viewbag doesn't required typecasting and is a dynamic property.

Here is how we can implement Viewbag.

Code snippet at Person controller's GetEmployeeDetails action method.
  1. public ActionResult GetEmployeeDetails()  
  2. {  
  3.     Employee empdetails = new Employee();  
  4.     empdetails._name = "Shridhar Sharma";  
  5.     empdetails._age = 25;  
  6.     empdetails._email = "[email protected]";  
  7.     empdetails._city = "New Delhi";  
  8.     //ViewData["Employeedetails"] = empdetails;  
  9.     ViewBag.Employeedetails = empdetails;  
  10.     return View("employeeview",empdetails);  
  11. }  
Here we are getting properties at View.



View Snippet
  1. @{  
  2.     Layout = null;  
  3.     ProjectMVC.Models.Employee empdetails = (ProjectMVC.Models.Employee)ViewBag.Employeedetails;     
  4.    
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>employeeview</title>  
  13. </head>  
  14. <body>         
  15.     <h1>Using Viewbag</h1>  
  16.             NAME : @empdetails._name  <br />      
  17.             AGE : @empdetails._age     <br />  
  18.             EMAIL : @empdetails._email     <br />  
  19.             CITY : @empdetails._city   
  20. </body>  
  21. </html>  
View
 
 
For strongly type view
  1. @model ProjectMVC.Models.Employee //model  
After adding above model, we can access all the properties of that model as follows.

It will reduce the probability of compile time error, which will definitely enhance the efficiency and productivity of a developer.

Closure

In this short article we focused simply on how we can store data to be passed over to view using Viewbag. I just hope you as a entry level developers found it helpful.

Happy Coding !


Similar Articles