5

I have a controller calling a view. In the view there is a partial view, inserted like this:

@{ Html.RenderPartial("PartialViewName", this.Model);} 

This works fine.

But in the controller I wish to put something in the ViewData or ViewBag that I will use in the partial view. How can I do this?

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
Victor
  • 235
  • 1
  • 5
  • 14

4 Answers4

6

You should be able to do this just fine. The View Bag and View Data are available during the entire life of the Action method so if you add an item to view data in the controller method that gets the view, any subsequent partials that are rendered on that view will have access to the view data. The syntax for getting a value from view data in your partial view is very easy. Example:

   @{
       var variable = ViewData["My Key"];
   }
Matt Mangold
  • 710
  • 1
  • 6
  • 10
4

Both Html.Partial and Html.RenderPartial have an overload that accepts a ViewDataDictionary. You can build a new one, or simply pass the existing one.

@{ Html.RenderPartial("_MyPartial", Model.Property, new ViewDataDictionary { ... });}

or

@{ Html.RenderPartial("_MyPartial", Model.Property, ViewData);}

I'm fairly certain ViewBag is accessible to your partial without the need to pass any parameters.

EDIT:

ViewBag and ViewData are definitely available to both partials and editor/display templates. You can edit them in your view before a subordinate view accesses them like this:

@{ ViewBag.MyNewValue = "..."; }
@Html.Partial("_MyPartial", Model)

Then in your partial:

@{ string myString = ViewBag.MyNewValue; }
PancakeParfait
  • 175
  • 1
  • 9
3

As the others have said, as long as you assign the ViewBag value in your action method, you should be able to access it in your partial view.

Also, you should be able to render the partial block like this:

@Html.Partial("PartialViewName", Model)

instead of this

@{ Html.RenderPartial("PartialViewName", this.Model);}.
justinb138
  • 411
  • 2
  • 6
2

You can do it by the simpliest way.

Just set Viewbag.sth = value; in your controller.

and in your partial use @ViewBag.sth

Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62