Here you will learn how to transfer data from Controller to View through ViewBag and ViewData.The main purpose of both ViewBag and ViewData is to transfer data from Controller to View.

ViewBag:

ViewBag is a dynamic property. ViewBag is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed. ViewBag is just a wrapper around the ViewData.

Follow these steps in order to pass data from Controller to View using ViewBag.

Step 1: Create a Model Class Student as shown below:

Step 2: Create List of Student in Controller and pass the total Students to ViewBag.Students as shown below:

Step 3: In the View write this code as shown below:

Data has been transfered from Controller to View through VIewBag as shown below:

 

ViewData:

ViewData is nothing but a dictionary of objects and it is accessible by string as key. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class.ViewData is used to pass List from Controller to View.

Follow these steps in order to pass data from Controller to View using ViewData.

Step 1: Create a Model Class Student as shown below:

Step 2: Create List of Student in Controller and pass the Students List to ViewData[“Students”] as shown below:

Step 3:  In the View write this code as shown below:

 

Data has been transfered from Controller to View through VIewData as shown below: