asp.net-mvc - 有没有办法使用 asp.net mvc Razor ViewEngine 使 @section 成为可选?

标签 asp.net-mvc razor viewengine

我有一个类似于以下内容的 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>
    }
}

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

编辑

在我的布局中,我有:
@if(IsSectionDefined("ContentRight")) 
{
    <div class="right">
        RenderSection("ContentRight")
    </div>
}

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

最佳答案

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

在我的页面上,我有:

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

然后在我的布局中,我有:
@if(IsSectionDefined("ContentRight") && (ViewBag.ShowContentRight == null ||ViewBag.ShowContentRight == true)) 
{
    <div class="right">
        RenderSection("ContentRight")
    </div>
}
else if(IsSectionDefined("ContentRight"))
{
    RenderSection("ContentRight")
}

如果定义了该部分,则必须呈现它,但如果没有内容,我不想要 <div>

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

关于asp.net-mvc - 有没有办法使用 asp.net mvc Razor ViewEngine 使 @section 成为可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4903289/

相关文章:

asp.net-mvc - 自定义 MVC razor View 引擎的间歇性 View 路径问题

unit-testing - 没有字符串的单元测试 MVC3 Razor 助手/ View

asp.net-mvc-3 - HTML编码字符串-ASP.NET Web窗体VS Razor View 引擎

asp.net-mvc - 路径中存在非法字符。 while 捆绑 javascript 文件

asp.net-mvc - 从 ASP.NET MVC2 升级到 MVC3 的原因

c# - 帮助开始使用 VS2010 构建 ASP.NET 网站

asp.net - 在 Asp.net MVC 4 项目的 UI 层中不保留任何业务逻辑

c# - Petapoco tt 文件错误

c# - 如何从 Razor、MVC 渲染 # Symbol

asp.net-mvc - 缩小的脚本仅在MVC4 BundleConfig中