Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 885
vinczemarton Avatar asked Apr 20 '11 11:04

vinczemarton


People also ask

Can we use ViewBag in partial view?

2. Pass Data to Partial View using ViewBag/ViewData. You can use ViewData / ViewBag to pass the information from the controller's action method to the View. ViewData uses ViewDataDictionary and ViewBag is just a wrapper around ViewData using dynamic feature.

How do you assign a ViewBag value in view?

You can assign a primitive or a complex type object as a value to ViewBag property. You can assign any number of properties and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.

Can we pass ViewBag from view to controller?

ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.

How do I pass a model into partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.


2 Answers

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 
like image 111
slfan Avatar answered Sep 23 '22 11:09

slfan


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) 
like image 23
Andzej Maciusovic Avatar answered Sep 23 '22 11:09

Andzej Maciusovic