| by Achyut Kendre | No comments

How to Communicate Data from Action To View?

ASP NET MVC 5

In this article we will try to understand how to communicate data from controller action to view.

Example Source Code: https://drive.google.com/file/d/18rhAi973kxqTGDpnOV3-gh11NDzlePkz/view?usp=sharing

Since Controller Action is method and View is file we should have some ways to communicate the result of processing to view to create the presentation we have following options –

  • View Bag
  • View Data
  • Temp Data
  • Model

View Bag: –

  • View Bag is used to communicate small data from action to view.
  • View Bag is dynamic object means you can create any name any type of property.
  • It can communicate data from action to view (one way).
  • ViewBag will be empty when you redirect.

To create any property in Vew Bag we can use the following syntax –

ViewBag.PropertyName=value;

ViewData:-

ViewData is another option to communicate data from action to view used to communicate small data from action to view.

  • It is used to communicate data from action to view one way.
  • It is dictionary object collection stores data in key value pair.
  • It will be also empty when you redirect.
  • It is more faster as compare to ViewBag

You can create the variables as follows –

Viewata["variablename"] =value;

TempData:-

This is one more way to communicate data from action to view.

  • It is used to communicate small data from action to view.
  • It is also dictionary collection of object.
  • This is again one way communicates data from action to view.
  • It maintains data between redirects.

You can create variables in temp data as follows –

TempData["variablename"]=value;

Model: –

Model Example: https://drive.google.com/file/d/166-3Wzf-qqB1TfCSlSCx_25lnX2M8CtI/view?usp=sharing

Model is last and most powerful option to communicate data from action to view or view back to action. (two way).

  • Model handle the data part of MVC.
  • Model is used to communicate large strongly typed data from action to view and view back to action.
  • Model is just a class located in models folder which contains data related code.
  • It generally contains public properties.

Action can communicate model object to a view if view is strongly typed view using methods –

View(Model object)
View("viewname",Model Object)

To convert the view to strongly typed view we use @model command at the beginning of the view as follows –

@model full model class path.

Once view is strongly typed we can use the @Model object to access the model data or model properties is the property of view.