Here's the situation I'm trying to solve:
I have a main shared layout with a single section @RenderSection("Menu") that I want to default to a standard menu for the majority of my pages, but I would like to replace/override that section in a few sub pages. Is this possible with Razor at this stage in the game?
I was hoping I could possibly define the default implementation of that section in _ViewStart.cshtml but it doesn't seem to like it.
Would a Menu Partial view be better for this situation?
Edit:
I'm getting the following error with this code now: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "menu".
_Layout.cshtml
<div id="menu">
@if (IsSectionDefined("menu"))
{
RenderSection("menu");
}
else {
<text>
<ul>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li><a href="#">Lookups</a>
<ul>
@Html.ActionLink("Product","Index","Product")
</ul>
</li>
</ul>
</text>
}
</div>
Index.cshtml
@section menu {
<ul>
<li>@Html.ActionLink("Product", "Index", "Product")</li>
<li>@Html.ActionLink("Form Type", "Index", "Product")</li>
<li>@Html.ActionLink("Supplier", "Index", "Product")</li>
</ul>
}
All you have to do is to place a style sheet in the Pages folder alongside the page that it is intended to affect. You just need to follow a specific naming convention, which is the Razor page file name with . css on the end. The bundled file itself is placed in the wwwroot folder when the application is published.
The RenderBody method indicates where view templates that are based on this master layout file should “fill in” the body content. Layout pages can also contain content that can be filled by other pages on disk. This is achieved by using the RenderPage method. This method takes either one or two parameters.
The _ViewStart. cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page. When a View Page Start is running, the “_ViewStart.
Ah... I was messing with this and found I could do it by just switching the logic around:
@RenderSection("Header", false)
@if (!IsSectionDefined("Header")) {
<header>
Default Header!
</header>
}
So if my pages don't define @section Header { ... }
, it renders the default.
The IsSectionDefined
method should suite your needs:
@if(IsSectionDefined("Menu")) {
@RenderSection("Menu")
} else {
<text>
Default Menu Content.
</text>
}
Update: I wrote a blog post to better illustrate the available options: Link
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