@RenderSection的目的是什么?它是如何工作的?我理解捆绑包的作用,但我还没有弄清楚它的作用,它可能很重要。

@RenderSection("scripts", required: false)

也许是一个关于如何使用它的小例子?


如果你有一个_Layout。像这样的CSHTML视图

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

然后你可以有一个索引。像这样的CSHTML内容视图

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

required指示使用布局页面的视图是否必须具有脚本部分


假设:

1. 你有一个_Layout。像这样的CSHTML视图。

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

2. 你有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.你有About.cshtml。

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

在你的布局页面上,如果required被设置为false: @RenderSection("scripts", required: false),当页面呈现并且用户在关于页面时,contacts.js将不会呈现。

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

如果required被设置为true: @RenderSection("scripts", required: true),当页面渲染并且user在About页面上时,contacts.js仍然会被渲染。

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

简而言之,当设置为true时,无论在其他页面上是否需要它,它都会被呈现。如果设置为false,则仅在呈现子页面时才呈现。


这里是来自MSDN的Rendersection的定义

在布局页中,呈现指定节的内容。MSDN

在_layout.cs页面中放置

@RenderSection("Bottom",false)

这里呈现底部节的内容,并指定false布尔属性来指定是否需要该节。

@section Bottom{
       This message form bottom.
}

这意味着如果你想在所有页面的底部部分,那么你必须使用false作为Rendersection方法的第二个参数。


假设我有getallemployes .cshtml

<h2>GetAllEmployees</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
         // do something ...
    </thead>
    <tbody>
       // do something ...
    </tbody>
</table>

   //Added my custom scripts in the scripts sections

@section Scripts
    {
    <script src="~/js/customScripts.js"></script>
    }

另一个视图“GetEmployeeDetails”。没有脚本的Cshtml

<h2>GetEmployeeByDetails</h2>

@Model.PageTitle
<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
       // do something ... 
    </thead>
    <tbody>
       // do something ...
    </tbody>
</table>

然后是布局页面_layout。cshtml

@RenderSection("Scripts", required: true)

所以,当我导航到GetEmployeeDetails.cshtml。我得到一个错误,在GetEmployeeDetails.cshtml中没有要呈现的节脚本。 如果我将@RenderSection()中的标志从required: true更改为' ' required: false '。这意味着呈现视图的@section脚本中定义的脚本(如果存在的话)。否则,什么都不做。 改进的方法将在_layout.cshtml中

@if (IsSectionDefined("Scripts"))
    {
        @RenderSection("Scripts", required: true)
    }