Using sections in ASP.NET MVC


In order to render the content of a section in an ASP.NET MVC layout page, we use the RenderSection method.

Sections usage

In ASP.NET MVC, a section is a piece of code that we want to render in a layout page. This allows us to render a specific view content in any location of a layout. In order to declare a section in a view, we use the @section keyword followed by the name of the section.

@section name { }



We use the RenderSection method to render the content of a section by passing its name as a parameter of the method.


The following is a section named scripts which contains a script tag that points to an external script file.

@section scripts{
    <script src="~/Scripts/file.js"></script>  

the objectif here is to render the above section's content at the bottom of our layout page. To do that, we go to the the bottom of the layout page and we use the RenderSection method like this :



If the section you are defining isn't used in all your views, you have to specify that it is not required in your layout page by passing false to the RenderSection method like this :

@RenderSection("scripts", false)

Otherwise, you will get the following error

Section not defined

See also