c# – 将数据从部分视图传递到其父视图

栏目: ASP.NET · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/19766502/passing-data-from-partial-view-to-its-parent-view

如果我有视图和部分视图,有什么方法可以将数据从部分视图传递给父视图?

所以,如果我有View.cshtml:

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

和_PartialView.cshtml:

@{ someDataFromPartialSomehow = "some-data" }

<div>
    Some content
</div>

我将如何实现这样的事情?

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

一次尝试

要尝试解决在调用之前生成的数据问题,我试过这个:

View.cshtml:

@{ var result = Html.Partial("_PartialView"); }

<div id="@ViewData["Stuff"]">
    @result
<div>

_PartialView.cshtml:

@{ ViewData["Stuff"] = "foo"; }

<div>
    Content
</div>

但是对@ViewDate [“Stuff”]的调用仍然没有遗憾.

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

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

然后:

@{ var result = Html.Partial("_PartialView"); }

<div id="@this.ViewContext.HttpContext.Items["Stuff"]">
    @result
<div>

除了您在问题中显示的示例:

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

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

还要记住,你想要实现的是糟糕的设计.如果部分视图只能在某个特定父级的上下文中工作,那么您可能需要重新考虑视图分离.部分视图必须是独立和可重用的,无论它在哪种上下文中.如果它假定托管父母的事情,那么这里有一个严重的设计问题.

翻译自:https://stackoverflow.com/questions/19766502/passing-data-from-partial-view-to-its-parent-view


以上所述就是小编给大家介绍的《c# – 将数据从部分视图传递到其父视图》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to Probability Theory and Its Applications

An Introduction to Probability Theory and Its Applications

William Feller / Wiley / 1991-1-1 / USD 120.00

Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试