Passing data from Partial View to parent view

If I have View and Partial View, is there a way to transfer data from Partial View to 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 can I implement something like this?

I tried using ViewBag.SomeDataFromPartialSomehow , but this only leads to null in the parent.


Attempt

To try to get around the generated data problem before the call, 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 calling @ViewDate["Stuff"] doesn't do anything yet.

+7
c # asp.net-mvc razor
source share
3 answers

You can split state between views using 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 for the example that you indicated in your question:

 <div id="@someDataFromPartialSomehow"> @Html.Partial("_PartialView") </div> 

you are trying to use someDataFromPartialSomehow even BEFORE , referring to a partial view, which is obviously impossible.

Also keep in mind that what you are trying to achieve is poor design. If a partial view can only work in the context of a specific parent, you may need to rethink your separation of views. Partial representations are what should be INDEPENDENT AND POSSIBLE, regardless of the context in which it is placed. If he accepts things about parent hosting, there is a serious design problem.

+19
source share

I have a suggestion for you.

Put the hidden input fields in a partial view and get them from javascript.

Example: In _PartialView.cshtml

 <input type="hidden" id="someDataFromPartialSomehow" value="5" /> 

In your opinion

 <script> $(document).ready(function(){ var someDataFromPartialSomehow = $("#someDataFromPartialSomehow").val(); }); </script> 

Note that you must write the js function inside the document ready function because the partial view must be fully loaded.

+3
source share

So, after some thought, I came up with this:

View.cshtml :

 @{ dynamic properties = new NullingExpandoObject(); var result = Html.Partial("_PartialView", (NullingExpandoObject)properties); } <div id="@properties.Id"> @result <div> 

_PartialView.cshtml :

 @{ Model.Id = "foo"; } <div> Content </div> 

Where NullingExpandoObject is a dynamic dictionary with a null value Jon Skeet

0
source share

All Articles