ASP.Net MVC Scribblings
  • Introduction
  • Introduction
    • My ASP.net MVC Scribblings
    • Test
  • ASP.net MVC
    • Routing
    • Passing Data in MVC
      • ViewData and ViewBag
      • ViewData / ViewBag
      • TempData
      • Session Variables
    • ModelBinder
    • Advantages of MVC over WebForms
    • Data Annotation
    • RAZOR
    • ActionName decorator for overloaded Controller actions
    • Security
      • CSRF
      • XSS
    • Shared Layout page
    • Custom Claims-based Windows Authentication in ASP.net MVC 5
Powered by GitBook
On this page

Was this helpful?

  1. ASP.net MVC
  2. Passing Data in MVC

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();
 }
}
PreviousViewData and ViewBagNextTempData

Last updated 5 years ago

Was this helpful?

To pass data from one action to another, use .

TempData