asp.net-mvc 什么是@section 脚本以及它的用途

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37727972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:33:04  来源:igfitidea点击:

What is @section scripts and what it is used for

asp.net-mvc

提问by Decoder94

I have downloaded a chat example from the Microsoft website. I have been following several tutorials but I have never seen the @section script{} before I have done scripts without this block of c# code (@section script{}) and it seem to work fine but in this instance of the chat application using signal R when I do take the scripts outside the block it does not work.

我已经从 Microsoft 网站下载了一个聊天示例。我一直在关注几个教程,但在我完成没有这个 c# 代码块(@section 脚本{})的脚本之前,我从未见过 @section 脚本{},它似乎工作正常,但在聊天应用程序的这个实例中使用当我将脚本带到块外时,信号 R 不起作用。

@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
    $(function () {
        // Reference the auto-generated proxy for the hub.
        var chat = $.connection.chatHub;
        // Create a function that the hub can call back to display messages.
        chat.client.addNewMessageToPage = function (name, message) {
            // Add the message to the page.
            $('#discussion').append('<li><strong>' + htmlEncode(name)
                + '</strong>: ' + htmlEncode(message) + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub.
                chat.server.send($('#displayname').val(), $('#message').val());
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        });
    });
    // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }
</script>
}

回答by BenG

A sectionallows you to add something in a view which will be added in the layout. ie:-

Asection允许您在视图中添加将添加到布局中的内容。IE:-

view

看法

@section scripts {

    <script>

      alert('foo');

    </script>

}

layout

布局

@RenderSection("scripts", false)

now this named sectionscriptswill be rendered where you have specified in the layout.

现在,此命名section脚本将呈现在您在布局中指定的位置。

@RenderSectionalso has 2 signatures:-

@RenderSection也有 2 个签名:-

public HelperResult RenderSection(string name) // section required in the view
public HelperResult RenderSection(string name, bool required)

回答by hvaughan3

When you define an @sectionsomewhere, lets say the _Layout.cshmtlfile, it allows all of your Views to dynamically insert script files or CSS files or what ever into places in the defining page.

当您定义某个@section地方时,比如说_Layout.cshmtl文件,它允许您的所有视图动态插入脚本文件或 CSS 文件或任何内容到定义页面中的位置。

This is very nice when, for example, you are using the jQuery UI Datepicker control only on a couple views in your site. So you may not want to globally include the jQuery UI Datepicker script file in your _Layout.cshtmlsince you are only going to need it on 2 or 3 pages.

例如,当您仅在站点中的几个视图上使用 jQuery UI Datepicker 控件时,这非常好。因此,您可能不想在您的全局中包含 jQuery UI Datepicker 脚本文件,_Layout.cshtml因为您只需要在 2 或 3 个页面上使用它。

@sectionallows you to include those files only for certain views. It is needed since, a view cannot easily change the contents of the _Layout.cshtmlotherwise.

@section允许您仅为某些视图包含这些文件。这是必需的,因为视图不能轻易更改其他内容的内容_Layout.cshtml

You can also position the @sectionat the bottom of the layout, for JavaScript files for example, or at the top of the layout, for CSS files. You could also use it to include a sidebar, made in HTML, only in certain views.

您还可以将@section放置在布局底部(例如 JavaScript 文件)或布局顶部(例如 CSS 文件)。您还可以使用它来包含仅在某些视图中用 HTML 制作的侧边栏。

Just be aware that Partial Views are not able to use the @sectionelement by default.

请注意,@section默认情况下部分视图无法使用该元素。

回答by Tekin

There is also one thing that should be added to the answers above that makes the use of "scripts" section crucial in most cases which is also the only reason for me to use this section.

还有一件事应该添加到上面的答案中,这使得在大多数情况下使用“脚本”部分至关重要,这也是我使用此部分的唯一原因。

That is, it guarantees that scripts will load after all page contents which is essential. By doing this, you actually make sure necessary elements for your JavaScript code have loaded already and also it is a matter of performance.

也就是说,它保证脚本将在所有必不可少的页面内容之后加载。通过这样做,您实际上可以确保已经加载了 JavaScript 代码的必要元素,这也是性能问题。

To elaborate how it works, I should mention that:

为了详细说明它是如何工作的,我应该提到:

  1. That is a common practice to put the commonly used scripts inside the "_Layout" page to make them accessible among all pages and also prevent their repetition.
  2. All contents of child views are loaded into the _Layoutview where @RenderBody()method is called. Except the contents inside @sectionsof each view.
  1. 将常用脚本放在“ _Layout”页面中是一种常见的做法,以使它们在所有页面之间都可以访问并防止它们重复。
  2. 子视图的所有内容都加载到调用@RenderBody()方法的_Layout视图中。除了每个视图的@sections内的内容。

When we define "scripts" section inside the footer of the layout for common scripts and then add our scripts of child views inside the "scripts" section of each child view we make sure that these scripts will load after the script of the layoutthat makes the functions in the _Layout available to the scripts of the child views.

当我们定义“脚本的布局,共同脚本的页脚中”部分,然后添加“里面我们的子视图脚本脚本每个子视图”一节中,我们确保这些脚本将布局的脚本之后加载,使得_Layout 中的函数可用于子视图的脚本。

Otherwise, the scripts of child views would be loaded where RenderBody() method is called, before the common scripts of the _Layout page.

否则,子视图的脚本将在调用 RenderBody() 方法的地方加载,在 _Layout 页面的公共脚本之前。

For Example:

例如:

Inside _Layout:

_Layout内部:

@RenderBody()
<footer>
    <script>
        $(function CommonlyUsedFunction() {
            console.log("text");
        });
    </script>
    @RenderSection("Scripts", required: false)
</footer>

Inside MyView:

MyView 中

<script>
    CommonlyUsedFunction(); //Function is not Accessible Here 
    //It will not be accessible because RenderBody() will load the function before its declaration.
</script>
@section Scripts
{
    <script>
        CommonlyUsedFunction(); //Function is Accessible Here
    </script>
}

回答by jamheadart

I'd just like to add another form of answer here, because it took me a combo of reading all three current answers and some experimenting before I understood it.

我只想在这里添加另一种形式的答案,因为在我理解之前,我需要阅读所有三个当前答案并进行一些实验。

I copied some ajax code for a modal popup that was enclosed in @section scripts { }and put it in a view. It worked fine, but I took away the sectionbit, because it was encapsulated in <script>html - which is normally fine;

我为包含在其中的模态弹出窗口复制了一些 ajax 代码@section scripts { }并将其放入视图中。它工作得很好,但我拿走了section一点,因为它被封装在<script>html 中——这通常很好;

My view before:

我之前的看法:

@Section scripts {
    <script> ... my function ... </script>
}
<h1>The rest of the page</h1>

How I normally include a one-off script on a view:

我通常如何在视图中包含一次性脚本:

<script> ... my function ... </script>
<h1>The rest of the page</h1>

By doing this, the script is rendered inside the html of the view itself and the popup stopped working. This is because the script accesses elements outside of that view - it needs site-wide access so to be able to stop using @section scriptsI would have to be put in the layout file.

通过这样做,脚本被呈现在视图本身的 html 中,并且弹出窗口停止工作。这是因为脚本访问该视图之外的元素 - 它需要站点范围的访问权限,以便能够停止使用@section scripts我必须放入布局文件中。

But I only really want this script rendered when this view is being used. I don't want to put it in the _layoutfile and have it loading on every single page.

但我真的只希望在使用此视图时呈现此脚本。我不想将它放在_layout文件中并在每个页面上加载它。

Lucky me! At the bottom of a default _layoutfile there's a line (I normally remove, to be honest):

幸运的我!在默认_layout文件的底部有一行(老实说,我通常会删除):

@RenderSection("scripts", required: false)

So by enclosing my <script>s in @section scripts { }on any view, it becomes part of the _layout, and is loaded after all other content (it's right at the bottom of the layout page), but only when that particular view is used.

因此,通过将 my <script>s包含@section scripts { }在任何视图中,它成为 的一部分_layout,并在所有其他内容之后加载(它就在布局页面的底部),但仅当使用该特定视图时

It basically allows a dynamic layout page which is very clever, I wonder if it's possible to do with stylesheets too.

它基本上允许一个非常聪明的动态布局页面,我想知道是否也可以使用样式表。