Difference between RenderBody and RenderSection
Start with @RenderBody
, this is vital. Your _layout has to have it. This is where your view will be rendered. If you leave it out, your app will die (I think on run time, as Views are not compiled).
[Correction: Without Renderbody, the View referencing this particular layout will die on run-time. (Important to note that layout are themselves optional.)]
Sections are code blocks defined within your View with similar names
@RenderSection("Navbar", required: false)could have a corresponding code block in your View.
@section Navbar{
<!-- Content Here -->
}
I emphasize could because the Navbar is delcared required: false
Sections are a way each View can share a piece of functionality / markup with the _layout.
Followup: In my modest time of MVC development I have learned to make modest use of sections.
- Sections are useful for making sure your JS references are placed in your HTML section (even though this is an antiquated practice.
- Sections are useful for top and side navs
- Sections never be required. To do so makes your code fragile!
RenderBody
is required, as it's what renders each view. RenderSection
has an optional parameter that lets you mark the section as not required.
Simply because of convenience. Rendering the body is something that you would most likely do so its good to have a dedicated function for that. Keeps you from declaring a @section for the body and gives an easier to call function.