1

When inside a razor view, can you pass data to the view from a child action? IE:

@{
   ViewBag.passedData = "";
}

@Html.Action("ChildView","ChildController") // Inside the child action (controller or view) magic happens

@ViewBag.passedData // it's not empty!

Note that inside child view, I can read the parent view data using ControllerContext.ParentActionViewContext.ViewBag.passedData but when I write to it, nothing happens.

Turns out that to access the .passedData property, one should use in the parent View:

  @ViewContext.ViewBag.passedData   // Has the passed data!
  @ViewBag.passedData // null

This will get the ball rolling but if there is a more proper or formal way to do this please reply.

Mihalis Bagos
  • 2,500
  • 1
  • 22
  • 32
  • nothing happens? place break points, step through your code, what DOES it do when it hits that point? the more info you can give the better – RhysW Jun 11 '12 at 14:30
  • Actually I am going to update with an solution but will still wait for a more formal/proper one (if there is) – Mihalis Bagos Jun 11 '12 at 14:33
  • 3
    Why are you using ViewBag/ViewData instead of strongly typed view models? What are you trying to achieve? Why are child actions supposed to modify some data used by the parent? I am sure that there are better ways to achieve whatever you are trying to achieve. – Darin Dimitrov Jun 11 '12 at 14:39
  • You keep saying you want a "proper or formal way." Using the ViewBag isn't the proper way. The proper way is to strongly type your views and pass your data around with your models. – Sean Jun 11 '12 at 15:21
  • http://stackoverflow.com/questions/7737124/does-a-child-action-share-the-same-viewbag-with-its-parents-action – VJAI Jun 11 '12 at 15:41
  • 1
    @Mark The link describes the other way around. Sean, I am trying to create a child view that passes back any dependencies (in css/js files) to the main view so that the main view can arrange/compile them. I am not against using the main model, although that lies in ViewData.Model so it requires access to the ViewData object anyway – Mihalis Bagos Jun 11 '12 at 17:30

0 Answers0