Passing data from controller to view / .NET MVC

Published on: Monday, 07.10.2024

ViewData and ViewBag are used to transfer data from controller to view.
ViewData is a dictionary of objects. It is a controller property that exposes an instance of the ViewDataDictionary class.

ViewData["Message"] = "Hello from ViewData!";

ViewBag is very similar to ViewData. ViewBag is a wrapper that provides dynamic properties for the underlying ViewData collection.

ViewBag.Message = "Hello from ViewBag!";

The best way is to pass a Model or ViewModel, a custom class specifically designed to structure data for a view.