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

Victor picture Victor · Jun 22, 2012 · Viewed 11.9k times · Source

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?

Answer

Matt Mangold picture Matt Mangold · Jun 22, 2012

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"];
   }