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