Can't access ViewData in a partial view in ASP.NET MVC3
Asked Answered
F

4

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?

Forworn answered 22/6, 2012 at 17:10 Comment(4)
You want to use ViewBag in your partial, or use ViewBag as model in your partial?Usually
Why is the data you need to consume not defined in the model you are passing to the partial view? (that's what that second parameter is for, after all)Saskatoon
@Mateusz Rogulski I want to get value of ViewBag in my partialForworn
@Kirk Woll yes the data i want to consume not define in the model its set in the controller (variable to test...)Forworn
J
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"];
   }
Joyless answered 22/6, 2012 at 17:24 Comment(0)
O
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; }
Outsmart answered 22/6, 2012 at 17:17 Comment(0)
T
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);}.
Trepang answered 22/6, 2012 at 17:49 Comment(0)
U
2

You can do it by the simpliest way.

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

and in your partial use @ViewBag.sth

Usually answered 22/6, 2012 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.