Razor syntax to render section based on condition

后端 未结 2 1649
难免孤独
难免孤独 2020-12-29 23:38

I got a view with Layout defined. In the layout, there is a section:

@RenderSection(\"JavaScript\", required: false)

In the view, based on a c

相关标签:
2条回答
  • 2020-12-30 00:10

    @section blocks can only appear in markup contexts.

    You can write

    @if (condition)
    { 
        <text>
            @section JavaScript
            {
                <script type="text/javascript>
                   $(document).ready(function(){
                     //bla...
                   });
                </script>
            }
        </text>
    }
    
    0 讨论(0)
  • 2020-12-30 00:15

    @if(condition) RenderSection(..)

    @Section Javascript{ 
            <script type="text/javascript>
               $(document).ready(function(){
                 //bla...
               });
            </script>
    }
    

    or in your layout:

    @RenderSection(..)
    

    and in your view:

    @section Javascript{ 
    if(condition) 
    {
        <script type="text/javascript">
            $(document).ready(function () {
                //bla...
            });
        </script>
    } 
    } 

    also see: Is there a way to make a @section optional with the asp.net mvc Razor ViewEngine?

    0 讨论(0)
提交回复
热议问题