Different ways to Pass Data from Controller to View in MVC

If you develop web applications in ASP.NET MVC, you should definitely learn how to pass your “Model” data to the “View” using the “Controllers”. This post will show you 4 different ways to accomplish that. There are different ways to pass data from Controller to View in MVC.

In this article, I am going to discuss the ideas about different ways to pass data from Controller to View in MVC. Please read our previous articles before moving on to this article where we discussed the Razor Engine in MVC Framework. As part of this article, we are going to discuss the following contents which are related to different ways to pass data from Controller to View in MVC.

Different ways to pass data from Controller to View in MVC

There are different ways to transfer data from controller to view or view to controller. Please see the below different types.

  • ViewBag
  • ViewData
  • ViewModel
  • TempData

ViewBag

  • ViewBag is a dynamic feature property of controllerbase class which was introduced in C# 4.0.
  • ViewBag can be used for transfer the data from controller to view and even view to view.

ViewData

  • ViewData also used to pass data from controller to view.
  • If you initialize objects in ViewData, those objects become accessible in the view.

ViewModel

  • ViewModel allows to transfer the custom model/complex data from controller to view.
  • You must be create a strongly typed View which is using the data model List. ViewData from Microsoft

TempData

  • TempData is used for transfer insensitive data from one action method to another of the same or a different controller.
  • It is very short live instance so you should only use it during the current and subsequent requests only.

we will discuss deep dive into each session in our upcoming article.

ViewBag
ViewData
ViewModel
TempData

Leave a Comment

Your email address will not be published. Required fields are marked *