Abayomi Omosehin
2 min readSep 14, 2020

--

VIEWDATA IN MVC

Sometimes you have to pass a data directly from the controller to the view to populate the view even when the Javascript has not loaded. It can be an object, a string ,list or a number.

In .NET, ViewData is one of the way we store data and transfer to the view.

ViewData is a dictionary of objects that has a key (string) and a value. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class. String data can be stored and used directly without the need for a cast, but you must cast other ViewData object values on the view.

So we are passing a list, string and an integer to the view. Note, that all this data except string must be cast to their data type for it to be used on the view.

The ViewData is cast so that we can loop through it. If a ViewData is empty it will return null. You can pass an ID with a ViewData to make an API call in a Javascript file. Another way you can also pass data is through ViewBag.

--

--