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

SoonDead picture SoonDead · Apr 20, 2011 · Viewed 83.2k times · Source

I have a controller calling a view. In the view there is a PartialView called be @Html.Partial("ViewName", model). This works fine.

But in the controller I wish to put something in the viewbag what would be hard to put in the viewmodel I pass to the view. The main view have no problem accessing the ViewBag, but in the PartialView it does not return anything.

Is it possible to use the ViewBag in this case or should I "hack" this data into the model I pass to the view (and the model I pass to the PartialView, and the model I pass to the PartialView nested in the first PartialView)?

Answer

slfan picture slfan · Apr 20, 2011

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