有没有办法使 @section 与 asp.net mvc Razor ViewEngine 可选?

发布于 2024-10-15 17:17:33 字数 970 浏览 8 评论 0原文

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

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.

Edit

In my layout i have:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

万人眼中万个我 2024-10-22 17:17:33

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

在我的页面上我有:

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

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

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

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

on my page i have:

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

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.

长不大的小祸害 2024-10-22 17:17:33

渲染器期望在布局文件中的某个时间调用该方法。您可以欺骗渲染器并使用“全局”条件(例如登录)。

@{
    ViewBag.content = RenderBody();
}
@if (Request.IsAuthenticated) {
        @ViewBag.content;
} 
else {
        @Html.Partial("_LoginPartial")
}

The renderer is expecting the method to be called sometime in the layout file. You can spoof the renderer and use "global" conditionals (think login).

@{
    ViewBag.content = RenderBody();
}
@if (Request.IsAuthenticated) {
        @ViewBag.content;
} 
else {
        @Html.Partial("_LoginPartial")
}
飘过的浮云 2024-10-22 17:17:33

具有 perf 的私有静态只读字段信息的扩展方法:

private static readonly FieldInfo RenderedSectionsFieldInfo = typeof(WebPageBase).GetField("_renderedSections", BindingFlags.Instance | BindingFlags.NonPublic);

public static void EnsureSectionsAreRegisteredAsRendered(this WebPageBase webPageBase, params string[] sectionNames)
{
    var renderedSections = RenderedSectionsFieldInfo.GetValue(webPageBase) as HashSet<string>;
    if (renderedSections == null)
    {
        throw new WebCoreException("Could not get hashset from private field _renderedSections from WebPageBase");    
    }
    foreach (var sectionName in sectionNames)
    {
        if (!renderedSections.Contains(sectionName))
        {
            renderedSections.Add(sectionName);
        }
    }
}

在您的 cshtml 中:

@{ this.EnsureSectionsAreRegisteredAsRendered("SectionName1", " SectionName2", "…"); }

是的,是的,是的......我知道......不好的反映!使用需要您自担风险:)

Extension method with private static readonly field info for perf:

private static readonly FieldInfo RenderedSectionsFieldInfo = typeof(WebPageBase).GetField("_renderedSections", BindingFlags.Instance | BindingFlags.NonPublic);

public static void EnsureSectionsAreRegisteredAsRendered(this WebPageBase webPageBase, params string[] sectionNames)
{
    var renderedSections = RenderedSectionsFieldInfo.GetValue(webPageBase) as HashSet<string>;
    if (renderedSections == null)
    {
        throw new WebCoreException("Could not get hashset from private field _renderedSections from WebPageBase");    
    }
    foreach (var sectionName in sectionNames)
    {
        if (!renderedSections.Contains(sectionName))
        {
            renderedSections.Add(sectionName);
        }
    }
}

In your cshtml:

@{ this.EnsureSectionsAreRegisteredAsRendered("SectionName1", " SectionName2", "…"); }

Yes, yes, yes.... I know.... bad reflection! Use at your own risk :)

慈悲佛祖 2024-10-22 17:17:33

我在视图基类中使用以下方法(来自这篇优秀的博客文章 http://haacked.com/archive/2011/03/05/defining-default-content-for-a-razor-layout-section.aspx/ ):

public HelperResult RenderSection(string name, Func<dynamic, HelperResult> defaultContents)
{
    if (IsSectionDefined(name))
    {
        return RenderSection(name);
    }
    return defaultContents(null);
}

如果您没有视图基类,我推荐一个,因为它可以让您向视图添加各种额外的功能。只需创建一个具有以下签名的类:public abstract class MyViewPage; : WebViewPage 然后在您的 web.config 中设置它:

<system.web.webPages.razor>
  <pages pageBaseType="MyViewPage">
    ...
  </pages>
</system.web.webPages.razor>

I use the following method in my view base class (from this excellent blog post http://haacked.com/archive/2011/03/05/defining-default-content-for-a-razor-layout-section.aspx/):

public HelperResult RenderSection(string name, Func<dynamic, HelperResult> defaultContents)
{
    if (IsSectionDefined(name))
    {
        return RenderSection(name);
    }
    return defaultContents(null);
}

If you don't have a view base class, I recommend one because it lets you add all sorts of little extra functionality to your views. Just create a class with the following signature: public abstract class MyViewPage<T> : WebViewPage<T> and then set it in your web.config:

<system.web.webPages.razor>
  <pages pageBaseType="MyViewPage">
    ...
  </pages>
</system.web.webPages.razor>
甜点 2024-10-22 17:17:33

您可以使用 IsSectionDefined Layout.cshtml 将整个部分包装在 if 语句中

@if (IsSectionDefined("ContentRight"))
{
    <div>
    @RenderSection(name: "ContentRight", required: false)
    </div>
}

您的 cshtml 页面:

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

You can wrap your whole section in an if statement with IsSectionDefined

Layout.cshtml:

@if (IsSectionDefined("ContentRight"))
{
    <div>
    @RenderSection(name: "ContentRight", required: false)
    </div>
}

Your cshtml page:

@section ContentRight
{    
    @if (mycollection != null && mycollection.Count() > 0)
    {   
    <h2>
        Stuff
    </h2>
    <ul class="stuff">
        @foreach (MyCollectionType item in mycollection )
        {
            <li class="stuff-item">@item.Name</li>
        }
    </ul>
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文