In this article, we will explore ViewData in ASP.NET Core MVC, understand how it works, and implement it with a practical example. Let’s break it down into simple steps!
What is ViewData in ASP.NET Core MVC?
ViewData is a mechanism in ASP.NET Core MVC that allows data to be passed from the Controller to the View. It’s a dictionary-based object derived from the ViewDataDictionary class, which stores data as key-value pairs.
However, ViewData has a few key characteristics:
- It is valid only for the current request — meaning data will not persist across redirects or new requests.
- It requires typecasting when retrieving data in the view, which can lead to errors if the casting is incorrect.
- It is case-sensitive — so
ViewData["Message"]andViewData["message"]would be treated as different keys.
ViewData is used to pass data from the Controller to the View. However, it is important to note that ViewData only works for the current request — its value cannot be retained across multiple requests.
ViewData is derived from the ViewDataDictionary class, which functions like a dictionary — storing data in key-value pairs. Since it holds data as object types, it requires typecasting to retrieve values in the View.
This typecasting can sometimes lead to runtime errors if the data is not cast properly.
using Microsoft.AspNetCore.Mvc;
namespace WebApplication2.Controllers
{
public class Demo4Controller : Controller
{
public IActionResult Index()
{
ViewData["Message"] = "Hi Message";
return View();
}
}
}
View
<h1>Index</h1>
Message: - @ViewData["Message"]
