我有以下布局模板:
- <div id="columns" class="@View.LayoutClass">
- <div id="mainColWrap">
- <div id="mainCol">
- @RenderBody()
- </div>
- </div>
- @if (View.ShowLeftCol){
- <div id="leftCol">
- @RenderSection("LeftCol",required: false)
- </div>
- }
- @if (View.ShowRightCol){
- <div id="rightCol">
- @RenderSection("RightCol",required: false)
- </div>
- }
- </div>
如果View.ShowLeftCol或View.ShowRightCol设置为false,我得到以下错误:
以下部分已定义,但尚未呈现为布局页“〜/ Views / Shared / _Layout.cshtml”:“RightCol”。
我试图有一个单一的布局模板,而不是试图在运行时动态选择一个模板。有没有办法忽略此错误并继续呈现?任何人都可以想到另一种方式实现,这将允许我动态显示/隐藏列与Razor?
谢谢!
解决方法
在
ASP.net论坛上工作的建议。
基本上,如果我定义@section LeftCol在我的视图模板,但不运行任何调用RenderSection在我的布局中的代码,我得到错误,因为它不会被调用时View.ShowLeftCol为false。建议添加一个else块,并且基本上扔掉LeftCol部分中的任何内容。
- @if (View.ShowLeftCol)
- {
- <div id="leftCol">
- @RenderSection("LeftCol",false)
- </div>
- }
- else
- {
- WriteTo(new StringWriter(),RenderSection("LeftCol",false));
- }
基于对记忆的关注,我决定测试以下。事实上,它也工作。
- @if (showLeft)
- {
- <section id="leftcol">
- <div class="pad">
- @RenderSection("LeftColumn",false)
- </div>
- </section>
- }
- else
- {
- WriteTo(TextWriter.Null,RenderSection("LeftColumn",false));
- }
另外,在我的页面的顶部,这是我的新逻辑为showLeft / showRight:
- bool showLeft = IsSectionDefined("LeftColumn");
- bool showRight = IsSectionDefined("RightColumn");
- bool? hideLeft = (bool?)ViewBag.HideLeft;
- bool? hideRight = (bool?)ViewBag.HideRight;
- if (hideLeft.HasValue && hideLeft.Value == true) { showLeft = false; }
- if (hideRight.HasValue && hideRight.Value == true) { showRight = false; }
有人说它不为他们工作,但它的工作方式像我一样的魅力。