Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

c# - Passing data from Partial View to its parent View

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...