Header add

 In this article we will discuss How to use ViewData in ASP.Net Core MVC.

Here we discuss What is ViewData with example of ViewData in ASP.NET Core MVC.

Before start this article, please visit our previous article How to use ViewBag in ASP.Net Core MVC

What is ViewData

ViewData is a dictionary of objects that are stored and retrieved using strings as keys. It is used to transfer data from Controller to View
  • 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.
  • Data is stored as Object in ViewData.
  • 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.
  • ViewData is used for passing value from Controller to View.
  • ViewData is available only for Current Request. It will be destroyed on redirection.

ViewData Example

Let's create a ASP.NET Core MVC project and pass data from controller to view.

Controller

In the controller we need to pass the data using ViewData object like in dictionary


View

In the view page we called here @ViewBag.Message, we need to remember whatever name is assign in ViewBag the same name must use to retrieve the data from view page and once the data can read then the ViewBag value is destroy.


When we run the application we can see the output like below.













Post a Comment

Previous Post Next Post