ASP.NET MVC: What is the purpose of @section?
It lets you define a @Section
of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.
//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);
Hope this helps.
A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.
How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?
You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.
In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.
Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.
Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.