MVC3 's Razor View engine also provides @rendersection
My understanding: @RenderSection occupy a single digit in the master page, and then let the child pages that use this master page render their section themselves.
Define @rendersection ("section name") in master page _layout.cshtml
<body>
<div id= "header" >@{html.renderaction ("menu", "Global");} </div>
<div id= "SideBar" >
@RenderSection ("submenu")
</div>
<div id= "Container" > @RenderBody () </div>
<div id= "Footer" >@{html.renderaction ("Footer", "Global");} </div>
</body>
Add a about.cshtml, use _layout.cshtml to make a master page
You can then define what "submenu" is going to render in about.cshtml
@{
Viewbag.title = "about";
}
@section submenu{
Hello This is a section implement on about View.
}
Here I implemented the submenu in about.cshtml, running the result
But when a page that uses _layout.cshtml as the master page does not implement section,
For example, my new index.cshtml does not implement @section submenu{...}, it throws an exception
This is because I am using @rendersection ("submenu") in _layout.cshtml, and he requires all the children to be implemented,
You can use one of its other overloaded @rendersection ("submenu", false), and the second parameter indicates that it is not required, so it does not throw an exception.
Also, when I define @rendersection ("submenu", false) in the master page, I want to not implement this section when all the sub-pages are
, the master page can have its own rendered content, which can be used
<div id= "SideBar" >
@if (issectiondefined ("submenu"))
{
@RenderSection ("submenu", false)
}
Else
{
<p>submenu section was not defined!</p>
}
</div>
This will display the defined content by default when no page renders the section.
MVC3 Razor @RenderSection