以下是我正在尝试解决的情况:
我有一个主共享布局,有一个单独的部分@RenderSection(“菜单”),我希望将其默认为大多数页面的标准菜单,但我希望在几个子页面中替换/覆盖该部分。在游戏的这个阶段,Razor可以做到这一点吗?
我希望我可以在_ViewStart.cshtml中定义该部分的默认实现,但它似乎不喜欢它。
在这种情况下,菜单局部视图会更好吗?
编辑:
我现在得到以下代码错误:以下部分已经定义,但还没有为布局页面"~/Views/Shared/_Layout.cshtml":"menu“呈现。
_Layout.cshtml
<div id="menu">
@if (IsSectionDefined("menu"))
{
RenderSection("menu");
}
else {
<text>
<ul>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li><a href="#">Lookups</a>
<ul>
@Html.ActionLink("Product","Index","Product")
</ul>
</li>
</ul>
</text>
}
</div>
Index.cshtml
@section menu {
<ul>
<li>@Html.ActionLink("Product", "Index", "Product")</li>
<li>@Html.ActionLink("Form Type", "Index", "Product")</li>
<li>@Html.ActionLink("Supplier", "Index", "Product")</li>
</ul>
}
发布于 2010-12-03 08:13:20
啊..。我对此进行了修改,发现只需切换一下逻辑就可以做到:
@RenderSection("Header", false)
@if (!IsSectionDefined("Header")) {
<header>
Default Header!
</header>
}
因此,如果我的页面没有定义@section Header { ... }
,它会呈现默认值。
发布于 2010-11-17 14:26:48
IsSectionDefined
方法应该适合您的需要:
@if(IsSectionDefined("Menu")) {
@RenderSection("Menu")
} else {
<text>
Default Menu Content.
</text>
}
更新:我写了一篇博文来更好地说明可用的选项:http://blogs.msdn.com/b/marcinon/archive/2010/12/08/Optional-Razor-Sections-with-Default-Content.aspx
发布于 2010-11-18 04:22:23
我目前正在使用多个布局来实现这个完全相同的场景。
/Views/Shared/_Layout.cshtml
<html>
...
<body>
<div id="menu">@RenderSection("Menu", required:false)</div>
...
@RenderBody()
...
</body>
</html>
/Views/Shared/_LayoutWithDefaultMenu.cshtml
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@section Menu { @Html.Partial("Menu") }
@RenderBody()
/Views/_ViewStart.cshtml
@{ Layout = "~/Views/Shared/_LayoutWithDefaultMenu.cshtml"; }
这意味着,在默认情况下,我的所有视图都使用默认菜单的布局。但是,在逐个视图的基础上,我可以将布局设置为_Layout.cshtml
,然后自己实现@section Menu
。
https://stackoverflow.com/questions/4201186
复制相似问题