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 10, 2019, 8:21 PM EST
Good one. Thanks
Aliya khanPosted Aug 21, 2019, 2:12 AM EDT
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, 1:53 AM EDT
Good one
Shridhar SharmaPosted Oct 7, 2015, 6:48 AM EDT
Thanks all for reading.
RakeshPosted Oct 6, 2015, 9:09 PM EDT
Good Share
Gowtham KTOP 100Posted Oct 6, 2015, 7:03 AM EDT
Good one
Sibeesh VenuTOP 100Posted Oct 6, 2015, 5:44 AM EDT
Nice Share
Harshad PansuriyaPosted Oct 6, 2015, 4:40 AM EDT
Nice One
Ankit BansalPosted Oct 5, 2015, 11:14 PM EDT
nice..
Nilesh JadavPosted Oct 5, 2015, 9:32 PM EDT
Nice one sir