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?
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.
Comments
Post a Comment