ASP.NET MVC: What is the purpose of @section?
asp.net-mvc
Solution
`@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.
Problem
For an ASP.NET MVC application, I saw this blog article. The author ScottGu adds `@section` to the Index.cshtml. I have a couple of questions (referring to the article above): - Is Index.cshtml a shared View? - The example code uses `@section` code in a particular view. Why? Can someone please explain why and when I would use `@section` in a View?