ViewData / ViewBag

To pass data from Controller to View - use ViewData or ViewBag

In controller's action code:

ViewData["MyData"] = "Some Example Data";

and you use it in View as below

<div>
    My data  I received from controller is: 
    @ViewData["MyData"]
</div>

ViewBag is syntactical sugar for ViewData, where instead of using array-like syntax(square brackets) to add a data-key, we use object-like syntax(. notation) to the add data-key:

But ViewBag uses dynamic keyword internally, which in turn uses reflections internally to figure out the datatype of data at the run time and hence usually more expensive process that simply using ViewData.

In controller's action code:

ViewBag.MyData = "Some Example Data";

and you use it in View as below

<div>
    My data  I received from controller is: 
    @ViewBag.MyData
</div>

ViewBag or ViewData can be passed only from a controller's action to view, its not passed from one action to another action.

You can redirect the control from one action to another action using the method RedirectToAction(<<actionName>>, <<controller>>)

public class HomeController: Controller{
 public ActionResult Index(){
     ViewBag.MyOriginalData = "Data from Index action"; // this data will not be available in the below action we are redirected to
     return RedirectToAction("Home", "Home");
 }

 public ActionResult Home() {
     ViewBag.MyData = "Some Example Data";
     return View();
 }
}

To pass data from one action to another, use TempData.

Last updated

Was this helpful?