带有级联部分的 Razor 嵌套布局 [英] Razor Nested Layouts with Cascading Sections

查看:19
本文介绍了带有级联部分的 Razor 嵌套布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Razor 作为其视图引擎的 MVC3 站点.我希望我的网站可以换肤.大多数可能的皮肤非常相似,可以从共享的主布局中派生出来.

I have an MVC3 site using Razor as its view engine. I want my site to be skinnable. Most of the possible skins are similar enough that they can derive from a shared master layout.

因此,我正在考虑这样的设计:

Therefore, I am considering this design:

但是,我希望能够在底层调用 RenderSection_Common.cshtml,并让它渲染在顶层定义的部分, Detail.cshtml.这不起作用:RenderSection 显然只渲染定义在下一层的部分.

However, I would like to be able to call RenderSection in the bottom layer, _Common.cshtml, and have it render a section that is defined in the top layer, Detail.cshtml. This doesn't work: RenderSection apparently only renders sections that are defined the next layer up.

当然,我可以定义每个皮肤中的每个部分.例如,如果 _Common 需要为 Detail 中定义的部分调用 RenderSection("hd"),我只需将它放在每个 _Skin 和它的工作原理:

Of course, I can define each section in each skin. For instance, if _Common needs to call RenderSection("hd") for a section defined in Detail, I just place this in each _Skin and it works:

@section hd {
    @RenderSection("hd")
}

这会导致一些代码重复(因为现在每个皮肤都必须有相同的部分)并且通常感觉很混乱.我还是 Razor 的新手,似乎我可能遗漏了一些明显的东西.

This results in some duplication of code (since each skin must now have this same section) and generally feels messy. I'm still new to Razor, and it seems like I might be missing something obvious.

调试时,我可以在WebViewPage.SectionWritersStack中看到已定义部分的完整列表.如果我可以告诉 RenderSection 在放弃之前查看整个列表,它会找到我需要的部分.唉,SectionWritersStack 是非公开的.

When debugging, I can see the complete list of defined sections in WebViewPage.SectionWritersStack. If I could just tell RenderSection to look through the entire list before giving up, it would find the section I need. Alas, SectionWritersStack is non-public.

或者,如果我可以访问布局页面的层次结构并尝试在每个不同的上下文中执行 RenderSection,我就可以找到我需要的部分.我可能遗漏了一些东西,但我看不出有什么办法可以做到这一点.

Alternatively, if I could access the hierarchy of layout pages and attempt execution of RenderSection in each different context, I could locate the section I need. I'm probably missing something, but I don't see any way to do this.

除了我已经概述的方法之外,还有其他方法可以实现这个目标吗?

Is there some way to accomplish this goal, other than the method I've already outlined?

推荐答案

这实际上在今天使用公共 API 是不可能的(除了使用节重新定义方法).使用私人反射可能会有些运气,但这当然是一种脆弱的方法.我们将研究在下一个版本的 Razor 中简化这个场景.

This is in fact not possible today using the public API (other than using the section redefinition approach). You might have some luck using private reflection but that of course is a fragile approach. We will look into making this scenario easier in the next version of Razor.

与此同时,这是我写的几篇关于这个主题的博文:

In the meantime, here's a couple of blog posts I've written on the subject:

这篇关于带有级联部分的 Razor 嵌套布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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