Sections in Layout View in ASP.NET Core MVC

Sections in Layout View in ASP.NET Core MVC

In this article, I will discuss the Sections in Layout View in ASP.NET Core MVC Application. Please read our previous article, where we discussed the Layout View in ASP.NET Core MVC Application. We will also work with the example we created in our previous article. As part of this article, we will discuss the following pointers.

  1. What are Sections in Layout View?
  2. Why Do We Need Sections in a Layout View?
  3. Understanding RenderSection and RenderSectionAsync Methods.
  4. How Do We Use the RenderSection Method in ASP.NET Core MVC?
  5. How to Provide Section Content in a Child View?
  6. Optional and Required Sections in ASP.NET Core MVC.
  7. How Do We Make the Layout Section Optional in ASP.NET Core MVC?
  8. RenderSection vs RenderSectionAsync Methods in ASP.NET Core MVC.
What are Sections in Layout View?

In ASP.NET Core MVC, the layout view is a shared template used to maintain a consistent look and feel across all the views in your application. You can use sections to inject content (such as custom JavaScript, stylesheets, or other unique blocks of HTML) from a child view into specific parts of the layout. So, Sections in ASP.NET Core MVC layout views provide a way to define content blocks that child views can fill.

This is useful in complex web applications with a common layout structure but varying content requirements across different pages. This mechanism is helpful for creating flexible and customizable layouts where different child views can inject their own content into specific sections of the layout.

Why Do We Need Sections in a Layout View?

To understand the Need for Sections in a Layout View, let us first create a custom JavaScript file. If it isn’t already there, create a folder at the root level of the application with the name wwwroot. As we create the project using Model-View-Controller, the wwwroot folder should be there.

In general, all the static files of our ASP.NET Core MVC Application need to be placed within this wwwroot folder. Once you have created the “wwwroot” folder, create a subfolder within it with the name “js” if it is not already there, and then add a Javascript file with the name “CustomJavascript.js” within the js folder.

To do so, right-click on the js folder and select Add => New Item from the context menu, which will open the New Item window. Here, search javascript, select Javascript File, give the file name CustomJavascript.js, and finally click the Add button, as shown in the image below.

Adding JavaScript File in ASP.NET Core MVC Application

Once you add the CustomJavascript.js file, your wwwroot folder should look as shown in the image below.

Sections in Layout View in ASP.NET Core MVC

Situation 1:

If we have a custom Javascript file (e.g., CustomJavascript.js) and all the views of our application require that file, we need to place that file in the Layout View of our application. Let us add that CustomJavascript.js file within our _Layout.cshtml file. So, modify the _Layout.cshtml file as follows.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">

        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>

    </table>
    <script src="~/js/CustomJavascript.js"></script>
</body>
</html>

Note: Putting all the script files before the closing body tag is always a good programming practice.

Situation 2:

Suppose we have a custom Javascript file (e.g., CustomJavascript.js), and we want this file to be used in some specific views. Let’s assume we want this file in the Index view but not in the Details view of the Home Controller. In such scenarios, we can use the Section in the ASP.NET Core MVC Application.

Understanding the RenderSection and RenderSectionAsync Method:

To use Section in ASP.NET Core MVC Layout Views, we are provided with the RenderSection and RenderSectionAsync methods. Let us look at the signatures of the RenderSection and RenderSectionAsync methods, shown below.

Understanding the RenderSection Method in ASP.NET Core MVC

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

  • name: The name of the section that you want to render.
  • required: A boolean value indicating whether the section is mandatory. If set to true, an exception is thrown if the section is not defined on the content page. If set to false, the layout will render without the section if it’s not present on the content page.
How Do We Use the RenderSection Method in ASP.NET Core MVC?

From your layout view, you need to call the RenderSection() method at the location where you want the section content to be rendered. For example, we want the script file to be included before the closing </body> tag. So, here, we are calling the @RenderSection() method just before the closing </body> tag, as shown below.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">

        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>

    </table>
    @RenderSection("Scripts")
</body>
</html>

In the above code, we use the first overloaded version of the RenderSection method, which only takes the name parameter. In this case, the second parameter value will be true by default. That means it is a mandatory section.

How to Provide Section Content in a Child View?

We have created a section in our layout view. Now, let us understand how to provide section content from the Child Views. Each view that wants to provide section content must include a section within the view. We need to use the @section directive to include the section and provide the content to do this.

In our example, we want to provide the section content from the Index view. So, modify the Index view as shown below. Here, you can see we are using @section Scripts {<script src=”~/js/CustomJavascript.js”></script>} as we are trying to include a javascript file. Here, we need to provide the section name as Scripts, and this is because, in the _Layout view, we have specified the section name as Scripts, i.e., @RenderSection(“Scripts”)

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Home Page</h1>
@section Scripts {
    <script src="~/js/CustomJavascript.js"></script>
}

Now run the application and navigate to the Home/Index URL, and you will see the out as expected, as shown in the below image.

How to Provide Section Content in a Child View?

But, when you navigate the Home/Details URL, you will get the following error page.

How to make the layout section optional in ASP.NET Core MVC

The reason for getting the above exception is the section is mandatory, and we have not specified the section content in the Details view. To verify this, go to the definition of the RenderSection(“Scripts”) method, which takes the string file name as a parameter, and you will see the following. As you can see, this method takes only the name parameter, and internally, it sets the required parameter value to true, making it mandatory to include the section in the child view. And in the Details view, we have not included any section.

RenderSection Method Signature in ASP.NET Core MVC

Optional and Required Sections in ASP.NET Core MVC

As mentioned, sections can be marked as required or optional in the layout:

  • Required Sections: If a section is marked as required in the layout and if the child view does not include that section, an exception will be thrown. 
  • Optional Sections: If a section is marked as optional (required: false), the layout will render without the section content if the child view does not define it. 
How Do We Make the Layout Section Optional in ASP.NET Core MVC?

We can make a layout section optional in ASP.NET Core MVC in two ways. They are as follows:

Option 1: Use the RenderSection method, which takes two parameters. Set the second parameter (i.e., the required) to false.
@RenderSection(“Scripts”, required: false)
So, modify the _Layout.cshtml file as shown below to make the section optional.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">

        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>

    </table>
    @RenderSection("Scripts", false)
</body>
</html>

With the above changes in place, run the application and navigate to both URLs. You should get the output as expected.

Option 2: Using the IsSectionDefined() method.

This method returns a value indicating whether the specified section is defined on the child view. If the section is defined in the child view, then the IsSectionDefined() method returns true, and in that case, the RenderSection method loads the content from the child view. If the method returns false, then the RenderSection method is not going to be executed and be ignored. So, modify the _Layout.cshtml file as shown below.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <table border="1" style="width:800px; font-family:Arial">

        <tr>
            <td colspan="2" style="text-align:center">
                <h3>Website Header</h3>
            </td>
        </tr>
        <tr>
            <td style="width:200px">
                <h3>Left Navigation Menus</h3>
            </td>
            <td style="width:600px">
                @RenderBody()
            </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center; font-size:x-small">
                <h3>Website Footer</h3>
            </td>
        </tr>

    </table>
    @if (IsSectionDefined("Scripts"))
    {
        @RenderSection("Scripts")
    }
</body>
</html>

With the above changes in place, run the application and navigate to both URLs. You should get the output as expected.

RenderSection vs RenderSectionAsync Methods in ASP.NET Core MVC

In ASP.NET Core MVC, RenderSection and RenderSectionAsync methods are used within layout pages to render sections from a view. The primary difference between the two methods lies in their mode of operation: synchronous versus asynchronous.

RenderSection

RenderSection is a synchronous method used in layout views to render a section defined in a view. The RenderSection method takes the section’s name as its first argument and an optional boolean parameter that indicates whether the section is required or not:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    @RenderBody()

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

In this example, @RenderBody() renders the main content of the view, while @RenderSection(“Scripts”, required: false) attempts to render a section named “Scripts”. The required: false parameter indicates that the section is optional; if the section isn’t defined in a view using this layout, the layout will still be rendered without throwing an error.

RenderSectionAsync

RenderSectionAsync is the asynchronous counterpart to RenderSection. It operates similarly in that it is used to render sections defined in views, but it does so asynchronously. This can be useful when the section’s content involves I/O operations, such as database calls or reading from files, which can be performed asynchronously to improve the performance of your application. The use of RenderSectionAsync looks similar to RenderSection, but it requires the await keyword because it is an asynchronous method:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    @RenderBody()

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Key Differences Between RenderSection and RenderSectionAsync Methods

RenderSection executes synchronously, while RenderSectionAsync executes asynchronously. RenderSectionAsync is preferred when the section content involves asynchronous operations. Using RenderSectionAsync can help prevent the web server thread from blocking, potentially improving the application’s overall performance.

In the next article, I will discuss the _ViewStart.cshtml in an ASP.NET Core MVC Application. In this article, I will try to explain the Sections in the layout page in an ASP.NET Core MVC Application.

5 thoughts on “Sections in Layout View in ASP.NET Core MVC”

  1. blank

    Not for publish :
    “CustomJavascript.js” within the js folder as shown in the below image.
    instead of
    “CustomJavascript.cs” within the js folder as shown in the below image.

  2. blank

    As you can see there are two overloaded versions of the RenderSection Method.
    instead of
    As you can there are two overloaded versions of the RenderSection Method.

Leave a Reply

Your email address will not be published. Required fields are marked *