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.
 
 

ViewData Example
In the below example, a string value is set in the ViewData object in Controller and it is then displayed in View.
Controller
public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewData["Message"] = "Hello MVC Core!";
        return View();
    }
}
 
View
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @ViewData["Message"]
</body>
</html>
 
 
Screenshot
Using ViewData in ASP.Net MVC Core
 
 
Downloads