ViewData and ViewBag are two techniques that allow passing data from controllers to views in ASP.NET MVC.
ViewData is a dictionary object that allows passing data as key-value pairs between the controller and the view. It is a property of the base class Controller and can be used to store and retrieve data in the same controller action. However, it has the limitation of being strongly typed, meaning that the key and value must be explicitly cast when retrieved in the view.
On the other hand, ViewBag is a dynamic object that allows passing data as properties from the controller to the view. Unlike ViewData, ViewBag is not type-safe, which means it does not require explicit casting to retrieve data in the view.
//ViewDatapublic ActionResult Index(){ ViewData["Message"] = "Hello, world!"; return View();}//ViewBagpublic ActionResult Index(){ ViewBag.Message = "Hello, world!"; return View();}//In View<h1>@ViewData["Message"]</h1><h1>@ViewBag.Message</h1>
//ViewData
public ActionResult Index()
{
ViewData["Message"] = "Hello, world!";
return View();
}
//ViewBag
ViewBag.Message = "Hello, world!";
//In View
<h1>@ViewData["Message"]</h1>
<h1>@ViewBag.Message</h1>
In general, ViewBag is easier to use but can be more error-prone than ViewData, as there is no compile-time checking. Therefore, it is recommended to use ViewData for strongly typed data and ViewBag for dynamic data.
Check below link
https://www.c-sharpcorner.com/blogs/difference-between-viewdata-viewbagtempdata-and-session-in-mvc-5
view data is dictionary object view bag is dynamic property
Check below linkViewData VS ViewBag Vs TempData in MVC
https://www.c-sharpcorner.com/blogs/viewdata-vs-viewbag-vs-tempdata-in-mvc1