ASP.NET CORE Mvc – Sections In Layout

In this tutorial we will discuss sections in a layout page in ASP.NET Core MVC and how to make use of section.

In ASP.NET Core MVC, the layout view contains one or more sections in it. The Sections in a layout view are used to organize where certain page elements should be placed. The sections in a layout view can be optional or mandatory.

To understand the section with example and use of section, we first create a subfolder within this with the name “js” under the wwwroot and then will add a javascript file with the name “custom.js” within the js folder.

Now let’s take scenario, If we have a custom javascript file (i.e. CustomJavascript.js) and that file is being required by all the views of our application, then we need to place it in the Layout View of our application. Your all javascript files should be placed  before the closing body tag and It is always a good programming practice.

Now let’s take a scenario. Our custom javascript is required in some specific views. Let assume you want that file in the StudentDetails view but not in the StudentList view of Student Controller. In such scenarios, we can make use of the section.

To make use of section we need to use @RenderSection method and need to give section name. If you a look at the definition of the RenderSection() method.

As you can see there are two overloaded versions of the RenderSection Method. The same is the case for the RenderSectionAsync method. The first version of the Render section method takes a single parameter (i.e. name) which specifies the name of the section. The second overloaded version takes two parameters. The first parameter (name) specifies the name of the section while the second parameter (required) specifies whether the section is required or optional.

In our layout view, we need to call the RenderSection() method at the location where you want the section content to be rendered. In our example, we want the script file to be included just before the closing tag. So, we are calling the @RenderSection() method just before the closing tag.

In our layout view, we have created a section. Now let us understand how to provide section content in a view. Each and every view which wants to provide section content must include a section within the same. Here, you need to use the @section directive to include the section and provide the content.

@section Scripts {
    
}

Now run the application and navigate to Student/Details/1 URL and you will see the out as expected. But, when you navigate to Student/StudentList URL, we will get the below error page.

The reason for getting the exception is the section is mandatory in our layout view and we have not specified the section content in the StudentList view. So lets make section optinal

 @RenderSection("Scripts", false);

You can watch our video version of this tutorial with step by step explanation.