Viewdata is the collection of
state that is passed to a view. A view should get all the information it needs
from the viewdata. It contains key/value pairs as well as some special
properties, such as Model. Viewdata is accessible on the controller as well. The
controller is responsible for filling the viewdata dictionary with objects. When
a view is executing, it will pull various object from viewdata while it is
rendering. If an expected object is not present, then you will see the same type
of exception present in any code using a dictionary collection in .Net.
How to use View Data?
Here, I am going to explain how to use ViewData in View to get the information
dynamically through Controller and Model.
HomeController.cs, we set the Current Date and Time by using
Now property of DateTime class in
the field of ViewData property.
//set the current date and
time in ViewData field
we created a property named as
FirstName that return a name.
After setting the data in ViewData, here in View we
retrieved the information in View through ViewData.
Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ViewData.Models.ModelClass>"
<!--Getting data from Model ViewData -->
<!--Getting data from Controller View Data
The current date and time is
The above code display output like below: