ASP.Net MVC 3剃刀:部分定义但未呈现错误

Sam*_*Sam 25 razor asp.net-mvc-3

我有以下布局模板:

<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>
Run Code Online (Sandbox Code Playgroud)

如果View.ShowLeftCol或View.ShowRightCol设置为false,则会出现以下错误:


已定义以下部分,但尚未针对布局页面"〜/ Views/Shared/_Layout.cshtml":"RightCol"进行渲染.


我正在尝试使用单个布局模板,而不是尝试在运行时动态选择模板.有没有办法忽略这个错误并继续渲染?任何人都可以想到另一种实现方式,这将允许我用Razor动态显示/隐藏列?

谢谢!

Sam*_*Sam 31

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));
}
Run Code Online (Sandbox Code Playgroud)

基于对内存的关注,我决定测试以下内容.确实它也有效.

@if (showLeft)
{
    <section id="leftcol">
        <div class="pad">
            @RenderSection("LeftColumn", false)
        </div>
    </section>
}
else
{
    WriteTo(TextWriter.Null, RenderSection("LeftColumn", false));
}
Run Code Online (Sandbox Code Playgroud)

另外,在我的页面顶部,这是我对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; }
Run Code Online (Sandbox Code Playgroud)

其他人说这对他们不起作用,但它对我来说就像是一种魅力.