I try to understand how works sections in Razor views. I have 2 layout files: _Layout.cshtml and _LayoutChild.cshtml which use the first layout inside. I try to declare sections in _Layout.cshtml and render it in the same file. Markup not appears but when I declare section in _LayoutChild.cshtml everything works. See example below:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
@RenderSection("A", false)
</head>
<body>
@section A{
<script>
alert("I'm in Layout!");
</script>
}
</body>
</html>
_LayoutChild.cshtml
@{
Layout = "_Layout";
}
@section A{
<script>
alert("I'm in LayoutChild!");
</script>
}
I understand that declaring section in the same file looks strange but I would like to know why it don't work?
While developing web site or application. Every page have some common section like header, footer, sidebar etc. Write and maintain these on every page is a hard job. So, we need a way to put them in one single place. Luckily in MVC we have Layout concept for this. We put all the common code in it and changing content in Views which will render in layout where we call @RenderBody() method.
Why we need sections ?
Some time we wanted to show specific content on some specific pages like newletters only show on blogs and home page, top news or some advertising banners on specific pages. For these type of scenarios sections rescue us in MVC.
How we can use section ?
We need to follow these two steps to used sections in MVC.
When views render then section content also added where we declare the section.
Code Example
1. Most of the time we need some specific javascript code for view. So we can do it like this
_Layout.cshtml
@RenderSection("scripts", required: false)
view.cshtml
@section scripts{
<script>
alert("I'm in Layout!");
</script>
}
2. News Letter example
_Layout.cshtml
@RenderSection("newletter", required: false)
view.cshtml
@section newletter{
<h3> New Letter </h3>
... rest of the html ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With