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

That should work without any problems. In my HomeController Index action I add a message to the ViewBag:

ViewBag.Message = "Welcome to ASP.NET MVC!";

On the Index View I add the partial view:

@Html.Partial("ViewName")

And on the partial view I render the message:

@ViewBag.Message

From the comments below: there seems to be a problem when you pass a model to the partial view. Then you can refer to the original ViewBag with

@ViewContext.Controller.ViewBag.Message

If you are using an overload of the Html.Partial() where viewData is one of the input parameters, for example:

@Html.Partial("PartialViewName", Model, new ViewDataDictionary(ViewBag))

then your partial view will not see data from your original ViewBag.

Remove new ViewDataDictionary(ViewBag), so you should write

@Html.Partial("PartialViewName", Model)

In a comment TehOne said:

I know this is a bit old, but for future reference, I solved this by using ViewContext.Controller.ViewBag.Property. Of course this means that the ViewBag property you are trying to access was set in the controller, but I think that is a common enough case.

Which is what worked for me.