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
)?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With