开发者

Razor syntax to render section based on condition

开发者 https://www.devze.com 2023-03-05 06:18 出处:网络
I got a view with Layout defined.In the layout, there is a section: 开发者_如何学C @RenderSection(\"JavaScript\", required: false)

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

开发者_如何学C

@RenderSection("JavaScript", required: false)

In the view, based on a condition, I want to either render certain JavaScript to the section or not.

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

The above syntax is wrong. What's the correct syntax?

Edit

Basically, I got a partial view which needs to be rendered based on a condition. If the condition is true, then I need to render the partial view together with some JavaScript for the partial view, which I want to go to the "JavaScript" section. How can I do that?


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


@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

精彩评论

暂无评论...
验证码 换一张
取 消