If I have a View and a Partial View, is there any way that I can pass data from the Partial View to the parent?
So if I have View.cshtml
:
<div id="@someDataFromPartialSomehow">
@Html.Partial("_PartialView")
</div>
And _PartialView.cshtml
:
@{ someDataFromPartialSomehow = "some-data" }
<div>
Some content
</div>
How would I go about implementing something like this?
I tried to use ViewBag.SomeDataFromPartialSomehow
, but this just results in null
in the Parent.
An attempt
To try get around the problem of data being generated before being called I tried this:
View.cshtml
:
@{ var result = Html.Partial("_PartialView"); }
<div id="@ViewData["Stuff"]">
@result
<div>
_PartialView.cshtml
:
@{ ViewData["Stuff"] = "foo"; }
<div>
Content
</div>
But the call to @ViewDate["Stuff"]
still renders nothing unfortunately.
ViewData 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 pass the strongly-typed data from Controller to View using ViewData, we have to make a model class then populate its properties with some data and then pass that data to ViewData dictionary as Value and selecting Key's name is the programmer's choice.
ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary.
You could share state between views using the HttpContext.
@{
this.ViewContext.HttpContext.Items["Stuff"] = "some-data";
}
and then:
@{ var result = Html.Partial("_PartialView"); }
<div id="@this.ViewContext.HttpContext.Items["Stuff"]">
@result
<div>
Except that the example you have shown in your question:
<div id="@someDataFromPartialSomehow">
@Html.Partial("_PartialView")
</div>
you are attempting to use the someDataFromPartialSomehow
even BEFORE invoking the partial view which obviously is impossible.
Also bear in mind that what you are trying to achieve is bad design. If a partial view can only work in the context of some specific parent, then you might need to rethink your separation of views. Partial views is something that must be INDEPENDENT and REUSABLE, no matter in which context it is being placed. If it assumes things about the hosting parent then there's a serious design problem here.
I have a suggestion for you.
Put hidden input fields in the partial view and get them from javascript.
Ex: In _PartialView.cshtml
<input type="hidden" id="someDataFromPartialSomehow" value="5" />
In your view
<script>
$(document).ready(function(){
var someDataFromPartialSomehow = $("#someDataFromPartialSomehow").val();
});
</script>
Note that you have to write the js function inside the document ready function because the partial view should be fully loaded.
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