Data sharing techniques in MVC

Action methods in controller process the request and prepare the result. This results present to the user with the help of the view.
To transfer the results from the controller to the view is achieved in the following ways:

  1. ViewData
  2. Viewbag
  3. Tempdata
  4. Strongly Typed View

1. ViewData

Viewdata is a built-in object of the view data dictionary class. Viewdata stores the data in key-value pairs.

Eg: viewdata [“total”]=2500;
Int t= (int)viewdata[“total”];

Note: Viewdata technique is introduced in MVC 1.0.

2. ViewBag

It is also used for sending the data from the controller to view. Viewbag is developed based on a dynamic concept of c# 4.0.

1.No need to perform typecasting.
2.Uses key as a property.

Eg: viewbag.Total =2500;
Int x=viewbag.Total;

Note: Here, viewdata and viewbag are available only in action method and corresponding view. Every action method having its own viewbag/viewdata objects.

3. Tempdata

Tempdata is available in current action and redirected action also. It is used to transfer the data from one action to another action at the redirection. Tempdata is an object of “Tempdatadictionary” class and it also stored the data in object format.

Eg: Tempdata [“name”]=”Scott”;
String strr= (string)tempdata[“name”]

4.Strongly typed view

If the view is designed by targeting specific model class object/objects, then that view is called “strongly typed view”. In STV, a view is a bind with corresponding model class object/objects.

1.No need to perform typecasting.
2.Supports compile-time type verification.
3.Supports intellisense.
4.More comfortable for database related operations.