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.
Here is how we can implement Viewbag.
Code snippet at Person controller's GetEmployeeDetails action method.
- public ActionResult GetEmployeeDetails()
- {
- Employee empdetails = new Employee();
- empdetails._name = "Shridhar Sharma";
- empdetails._age = 25;
- empdetails._email = "[email protected]";
- empdetails._city = "New Delhi";
- //ViewData["Employeedetails"] = empdetails;
- ViewBag.Employeedetails = empdetails;
- return View("employeeview",empdetails);
- }
Here we are getting properties at View.

View Snippet

View Snippet
- @{
- Layout = null;
- ProjectMVC.Models.Employee empdetails = (ProjectMVC.Models.Employee)ViewBag.Employeedetails;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>employeeview</title>
- </head>
- <body>
- <h1>Using Viewbag</h1>
- NAME : @empdetails._name <br />
- AGE : @empdetails._age <br />
- EMAIL : @empdetails._email <br />
- CITY : @empdetails._city
- </body>
- </html>
For strongly type view
- @model ProjectMVC.Models.Employee //model

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

Dinesh GabhanePosted Nov 11, 2019, 1:21 AM
Good one. Thanks
Aliya khanPosted Aug 21, 2019, 6:12 AM
How can i save data into Db if i have data in ViewBag?like i have Viewbag.otp=strrandom, i want to safe it in Db table col named as Otp?help?
Santhakumar MunuswamyPosted Oct 18, 2015, 5:53 AM
Good one
Shridhar SharmaPosted Oct 7, 2015, 10:48 AM
Thanks all for reading.
RakeshPosted Oct 7, 2015, 1:09 AM
Good Share
Gowtham KPosted Oct 6, 2015, 11:03 AM
Good one
Sibeesh VenuPosted Oct 6, 2015, 9:44 AM
Nice Share
Harshad PansuriyaPosted Oct 6, 2015, 8:40 AM
Nice One
Ankit BansalPosted Oct 6, 2015, 3:14 AM
nice..
Nilesh JadavPosted Oct 6, 2015, 1:32 AM
Nice one sir