In this article I will explain a short tutorial with example on how to use ViewData in ASP.Net MVC Core 2.1.
ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object used for passing data from Controller to View.
What is ViewData
1. ViewData is derived from the ViewDataDictionary class and is basically a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in ViewData.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. ViewData is used for passing value from Controller to View.
5. ViewData is available only for Current Request. It will be destroyed on redirection.
In the below example, a string value is set in the ViewData object in Controller and it is then displayed in View.
public class HomeController : Controller
public IActionResult Index()
ViewData["Message"] = "Hello MVC Core!";
Layout = null;
<meta name="viewport" content="width=device-width"/>