将数据从部分视图传递到其父视图 [英] Passing data from Partial View to its parent View

查看:83
本文介绍了将数据从部分视图传递到其父视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个View和Partial View,我有什么方法可以将数据从Partial 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?

所以,如果我有View.cshtml:

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

_PartialView.cshtml:

@{ someDataFromPartialSomehow = "some-data" }

<div>
    Some content
</div>

我将如何实现这样的目标?

How would I go about implementing something like this?

我尝试使用ViewBag.SomeDataFromPartialSomehow,但这只会在父级中导致null.

I tried to use ViewBag.SomeDataFromPartialSomehow, but this just results in null in the Parent.

尝试

要尝试解决在被调用之前生成数据的问题,我尝试了以下方法:

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>

但不幸的是,对@ViewDate["Stuff"]的调用仍然没有呈现任何结果.

But the call to @ViewDate["Stuff"] still renders nothing unfortunately.

推荐答案

您可以使用HttpContext在视图之间共享状态.

You could share state between views using the HttpContext.

@{
    this.ViewContext.HttpContext.Items["Stuff"] = "some-data";
}

然后:

@{ 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>

您正在尝试使用someDataFromPartialSomehow甚至之前来调用部分视图,这显然是不可能的.

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.

这篇关于将数据从部分视图传递到其父视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆