根据使用页面中定义的值在布局中呈现html内容

时间:2018-07-11 05:49:33

标签: c# asp.net-mvc razor

有没有一种方法可以在MVC页面中定义由布局文件使用的值或部分,以在布局文件中显示可选内容。

_Layout.cshtml

@if (someValueToCheck)
{
    //HTML content that will render on every page requiring this content
}

Somepage.cshtml

@{
   // set someValueToCheck to notify the Layout to render content
}

2 个答案:

答案 0 :(得分:1)

我认为无法做到这一点,最近的方法是定义几乎相同的布局文件,但这仍然很丑陋,因此以下内容可能会更好:

_Layout2.cshtml

@RenderPage("_Layout")

<div class="common-body-container">
    <div class="common-body-container-header">
        <div class="common-body-container-page-title">blah blah!</div>
    </div>
    <div class="common-body-container-contents">
        @RenderBody()
    </div>
</div>

这样,我不会重新定义几乎相同的布局文件,也不会重复在evey页面上构成容器的HTML标签。

编辑:感谢@ErikPhilips [stmt.iter]/3的诀窍,只有在内容页面中定义了部分时,它才会从布局中呈现可选内容:

_Layout.cshtml

@if(IsSectionDefined("commonBodyContainer")){
    <div class="common-body-container">
       <div class="common-body-container-header">
           <div class="common-body-container-page-title">blah blah!</div>
       </div>
       <div class="common-body-container-contents">
           @RenderSection(commonBodyContainer)
       </div>
    </div>    
} else {
    @RenderBody()
}

答案 1 :(得分:0)

部分通常用于定义页面中的内容,并显示在布局中。因此,如果您实际上是在尝试 完成该任务,那么它将看起来像:

_Layout.cshtml

@if(IsSectionDefined("optionalSection")){
  <div class="optional-content">
       @RenderSection(commonBodyContainer)
  </div>    
} 

@RenderBody()

renderOptionalContent.cshtml

@section optionalSection 
{ 
  <div>Content for opional-content</div>
}

如果您不需要渲染从视图传递到布局的内容,我更喜欢创建一个强类型的描述性方法来执行逻辑并将值存储在ViewData中。

internal static class WebViewPageExtensions
{
    const string ViewDataContentBlahKey = "ContentBlahKey";

    public static void SetShowContentBlah(this WebViewPage instance
       ,bool value)
    {
      instance.ViewData[ViewDataContentBlahKey] = value;
    }

    public static void GetShowContentBlah(this WebViewPage instance)
    {
      // if it's not set to false, it will be null
      var result = instance.ViewData[ViewDataContentBlahKey] as bool?;
      return result.HasValue && result.Value;
    }
}

_Layout.cshtml

@if(GetShowContentBlah())){
  <div class="optional-content">
    My Optional Content
  </div>    
} 

renderOptionalContent.cshtml

@{ SetShowContentBlah(true); }