ASP.Net MVC 3剃须刀:部分定义,但不会呈现错误 [英] ASP.Net MVC 3 Razor: Section Defined But Not Rendered Error

查看:115
本文介绍了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>

如果View.ShowLeftCol或View.ShowRightCol都设置为false,我得到以下错误:

If View.ShowLeftCol or View.ShowRightCol are set to false, I get the following error:

下面的路段已确定,但尚未呈现为页面布局〜/查看/共享/ _Layout.cshtml:RightCol。

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "RightCol".

我想有一个布局模板,而不是试图动态地选择在运行时的模板。有没有办法忽略这个错误并继续呈现?谁能想到另一种方式来实现,让我来动态显示/隐藏列剃刀?

I am trying to have a single layout template instead of trying to dynamically select a template at runtime. Is there a way to ignore this error and continue rendering? Can anyone think of another way to implement that would allow me to dynamically show/hide columns with Razor?

谢谢!

推荐答案

被赋予在 ASP.net 论坛工作的。

从本质上讲,如果我在视图模板中定义@section LeftCol但不运行任何code,在我的布局要求RenderSection,我得到的错误,因为它不会被调用时View.ShowLeftCol是假的。该建议是添加一个else块,基本上丢掉一切内容都在LeftCol部分。

Essentially, if I define @section LeftCol in my view template but don't run any code that calls RenderSection in my layout, I get the error because it doesn't get called when View.ShowLeftCol is false. The suggestion was to add an else block and essentially throw away whatever contents are in the LeftCol section.

@if (View.ShowLeftCol)
{ 
<div id="leftCol"> 
    @RenderSection("LeftCol", false) 
</div> 
}
else
{
    WriteTo(new StringWriter(), RenderSection("LeftCol", false));
}


根据提出关于内存的关注我决定测试下出为好。事实上,它也可以。


Based on the concern raised about memory I decided to test the following out as well. Indeed it also works.

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

此外,在我的页面的顶部,这是我showLeft / showRight新的逻辑:

Also, at the top of my page, this is my new logic for 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; }

别人说,他们没有为他们工作,但它的工作像一个魅力对我来说。

Someone else said it didn't work for them, but it worked like a charm for me.

这篇关于ASP.Net MVC 3剃须刀:部分定义,但不会呈现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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