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

asp.net-mvc-3partial-viewsviewdata

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?

Best Answer

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