Is it possible to make Razor sections optional?

后端 未结 5 1341
悲哀的现实
悲哀的现实 2021-01-11 11:45

If I have a page with:


    @section SomeStuff {
        This is a section I just addered
    }




        
相关标签:
5条回答
  • 2021-01-11 12:25

    You could do:

      @if (condition) {
         @RenderSection("SomeStuff")
      }
    

    Or just use a conditional statement directly rather than @RenderSection:

     @if (yourCondition) {
        <span>This is a section I just addered</span>
     }
    
    0 讨论(0)
  • 2021-01-11 12:26

    You can set a section to be optional by setting the required parameter to false. If you'd like to include some optional wrapper HTML around your section then you can also use the IsSectionDefined method.

    @if(IsSectionDefined("SideBar"))
    {
        <div class="sidebar">
            @RenderSection("SideBar", required: false)
        </div>
    }
    
    0 讨论(0)
  • 2021-01-11 12:31

    I encountered a similar issue when I was trying to dynamically inject code into an inline script, I solved it via:

    @if (someCondition)
        {
            @Html.Raw(@"
                  Your stuff here
            ");
        }
    
    0 讨论(0)
  • 2021-01-11 12:40

    you can specify if a section is required.

    @RenderSection("SomeStuff", required: false)
    

    if you don't render it out in a view, it shouldn't error then, noted here

    http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx

    0 讨论(0)
  • 2021-01-11 12:45

    For a certain layout not to render certain section you need to have something like this is your layout.cshtml

    @RenderSection("Somestuff", required:false)
    
    0 讨论(0)
提交回复
热议问题