What is @RenderSection in asp.net MVC - Stack Overflow

What is @RenderSection in asp.net MVC - Stack Overflow

What is the purpose of @RenderSection and how does it function? I understand what bundles do, but I have yet to figure out what this does and it's probably important.

@RenderSection("scripts", required: false)

Perhaps a small example on how to use it?

 

回答1

If you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()
        @RenderSection("scripts", required: false)
    </body>
</html>

then you can have an index.cshtml content view like this

@section scripts {
     <script type="text/javascript">alert('hello');</script>
}

the required indicates whether or not the view using the layout page must have a scripts section

 

回答2

Supposing that:

1. You have a _Layout.cshtml view like this.

<html>
    <body>
        @RenderBody()
       
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    @RenderSection("scripts", required: false)
</html>

2. You have Contacts.cshtml.

@section Scripts{
    <script type="text/javascript" src="~/lib/contacts.js"></script>

}
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

3. You have About.cshtml.

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>    Contacts</h2>
    </div>
</div>

On your layout page, if required is set to false: @RenderSection("scripts", required: false), when the page renders and the user is on the about page, contacts.js won't render.

    <html>
        <body><div>About<div>             
        </body>
        <script type="text/javascript" src="~/lib/layout.js"></script>
    </html>

If required is set to true: @RenderSection("scripts", required: true), When page renders and user is on the About page, contacts.js still gets rendered.

<html>
    <body><div>About<div>             
    </body>
    <script type="text/javascript" src="~/lib/layout.js"></script>
    <script type="text/javascript" src="~/lib/contacts.js"></script>
</html>

IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-10-16 炉石传说,佣兵战纪 技巧
2019-10-16 Are query string keys case sensitive?浏览器种输入url附带的参数是否区分大小写
2018-10-16 NOT IN clause and NULL values
2017-10-16 GitBlit中出现 error: remote unpack failed: error Missing tree
2015-10-16 default parameter value for ‘color’ must be a compile-time constant
点击右上角即可分享
微信分享提示