Cannot access ViewData in partial view in ASP.NET MVC3

I have a controller that calls a view. The view has a partial view inserted as follows:

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

This works great.

But in the controller, I want to put something in the ViewData or ViewBag, which I will use in a partial view. How can i do this?

+5
source share
4 answers

. Action, , , , , , , . :

   @{
       var variable = ViewData["My Key"];
   }
+6

Html.Partial Html.RenderPartial , ViewDataDictionary. .

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

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

, ViewBag - .

EDIT:

ViewBag ViewData, , , /. , :

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

:

@{ string myString = ViewBag.MyNewValue; }
+4

You can do this in the easiest way.

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

and with partial use @ViewBag.sth

+2
source

As others have said, as long as you assign a ViewBag value in your action method, you must have access to it in your partial view.

In addition, you should be able to display a partial block as follows:

@Html.Partial("PartialViewName", Model)

instead of this

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

All Articles