有没有一种方法,使@section可选与asp.net的MVC剃刀视图引擎? [英] Is there a way to make a @section optional with the asp.net mvc Razor ViewEngine?

查看:347
本文介绍了有没有一种方法,使@section可选与asp.net的MVC剃刀视图引擎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Page.cshtml similar to the following (that does not work):

@{
    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>
    }
}

正如我所说的,这是行不通的。我想如果有什么的集合中没有定义部分。有什么办法让这样的工作?如果没有,什么是我的其他选择?我很新的这剃刀视图引擎。

As I said, this does not work. I want to not define the section if there's nothing in the collection. Is there any way to have something like this work? If not, what are my other options? I'm very new to this Razor ViewEngine.

修改

在我的布局,我有:

@if(IsSectionDefined("ContentRight")) 
{
    <div class="right">
        RenderSection("ContentRight")
    </div>
}

我不希望是div输出时部分是空的。

what i don't want is the div to output when the section is empty.

推荐答案

我最后做的东西有点哈克得到它的工作我怎么需要它。

I ended up doing something a little hacky to get it working how I needed it.

我的网页上,我有:

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

然后我的布局我有:

then in my layout i have:

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

如果该部分被定义它必须被渲染,但如果没有内容,我不想在&LT; D​​IV&GT; 取值

If the section is defined it has to be rendered, but if there's no content i dont want the <div>s

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

If there's a better way i'd like to know.

这篇关于有没有一种方法,使@section可选与asp.net的MVC剃刀视图引擎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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