有没有办法用asp.net mvc Razor ViewEngine制作一个@section可选?

Joh*_*ker 7 asp.net-mvc viewengine razor

我有一个类似于以下的Page.cshtml(不起作用):

@{
    Layout = "../Shared/Layouts/_Layout.cshtml";
    var mycollection = (ViewBag.TheCollection as IQueryable<MyCollectionType>);
}

<h2>@ViewBag.Title</h2>

content here

@if (mycollection != null && mycollection.Count() > 0)
{    
    @section ContentRight
    {    
        <h2>
            Stuff
        </h2>
        <ul class="stuff">
            @foreach (MyCollectionType item in mycollection )
            {
                <li class="stuff-item">@item.Name</li>
            }
        </ul>
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,这不起作用.如果集合中没有任何内容,我想不定义该部分.有没有办法让这样的工作?如果没有,我的其他选择是什么?我对这款Razor ViewEngine非常陌生.

编辑

在我的布局中我有:

@if(IsSectionDefined("ContentRight")) 
{
    <div class="right">
        RenderSection("ContentRight")
    </div>
}
Run Code Online (Sandbox Code Playgroud)

我不想要的是当该部分为空时输出的div.

Joh*_*ker 3

我最终做了一些有点古怪的事情来让它按照我需要的方式工作。

在我的页面上我有:

@{
    Layout = "../Shared/Layouts/_Layout.cshtml";
    var mycollection = (ViewBag.TheCollection as IQueryable<MyCollectionType>);
    ViewBag.ShowContentRight = mycollection != null && mycollection.Count() > 0;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的布局中我有:

@if(IsSectionDefined("ContentRight") && (ViewBag.ShowContentRight == null ||ViewBag.ShowContentRight == true)) 
{
    <div class="right">
        RenderSection("ContentRight")
    </div>
}
else if(IsSectionDefined("ContentRight"))
{
    RenderSection("ContentRight")
}
Run Code Online (Sandbox Code Playgroud)

如果定义了该部分,则必须渲染它,但如果没有内容,我不希望<div>s

如果有更好的方法我想知道。