ViewBag and ViewData In Asp.Net MVC

In this article we will under stand How to Pass Data From Controller to View by Sagar Jaybhay.

How to Pass Data From Controller to View using ViewBag and ViewData?

ViewBag and ViewData In Asp.Net MVC
ViewBag and ViewData In Asp.Net MVC

Both are used to pass data from controller to view.

ViewData is a dictionary of objects which store and retrieve the data based on key.

ViewData["Today"] = DateTime.Now;

See the above code.

ViewBag uses the dynamic keyword internally and the dynamic keyword is introduced in C# v4. It allows objects to add as properties.

ViewBag.list = list;

See the above code.

In this, both do not provide compile-time error checking. Means if given ABC as a key name in the controller and in view if you misspell Abc then it will not provide compile-time checking. You will get the error at runtime only. It is good practice to pass data from controller to view using a strongly typed model.

ViewBag is a sugar coating over ViewData. Internally ViewBag properties are stored name-value pair list.

GitHub – https://github.com/Sagar-Jaybhay/MVC5

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Sagar Jaybhay

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

You may also like...