Mvc4 '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.
in the Master Page _layout.cshtml Define @rendersection ("section name") in
<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
and then you can be onabout. Define what "submenu" is to be rendered in cshtml
@{ viewbag.title = "About",} @section submenu{ Hello This is a section implement in 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 another overload of it @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.
-----------------------------------------------------------------------------------
There is also a more flexible approach, which is implemented by means of an extension method.
public static class Utility {public static Helperresult rendersection (this webpagebase page, string sectionname , Func<object, helperresult> defaultcontent) { if (page. Issectiondefined (sectionname)) { return page. Rendersection (sectionname); } else { return defaultcontent (null); } } }
In the master page
@this. Rendersection ("submenu", @<div>default section content</div>)
It's OK! When no section is rendered, it is displayed by default
<div>default Section content</div>
.
MVC4 Razor @RenderSection-master page settings