What is @section scripts and what it is used for

asp.net Mvc

asp.net Mvc Problem Overview


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.

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

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

view

@section scripts {

    <script>
      
      alert('foo');
      
    </script>

}

layout

@RenderSection("scripts", false)

now this named section scripts will be rendered where you have specified in the layout.

@RenderSection also has 2 signatures:-

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

Solution 2 - asp.net Mvc

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

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.cshtml since you are only going to need it on 2 or 3 pages.

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

You can also position the @section at 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.

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

Solution 3 - asp.net Mvc

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.

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 _Layout view where @RenderBody() method is called. Except the contents inside @sections of each view.

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 layout that makes the functions in the _Layout available to the scripts of the child views.

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

For Example:

Inside _Layout:

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

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

Solution 4 - asp.net Mvc

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 section bit, because it was encapsulated in <script> html - which is normally fine;

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 scripts I would have to be put in the layout file.

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

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDevView Question on Stackoverflow
Solution 1 - asp.net MvcBenGView Answer on Stackoverflow
Solution 2 - asp.net Mvchvaughan3View Answer on Stackoverflow
Solution 3 - asp.net MvcTekinView Answer on Stackoverflow
Solution 4 - asp.net MvcjamheadartView Answer on Stackoverflow