Instead of WebPageBase I used RazorPage in Microsoft.AspNet.Mvc.Razor
namespace Stackoverflow { public static class SectionExtensions { public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, Func<dynamic, IHtmlContent> defaultContents) { return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents(null); } } }
Then specify the class on the @using static Stackoverflow.SessionExtensions razor page and call it like this:
@this.RenderSection("extra", @<span>This is the default!</span>))
an alternative way would be to simply do this in a view (I prefer this way, it seems a lot easier):
@if (IsSectionDefined("extra")) { @RenderSection("extra", required: false) } else { <span>This is the default!</span> }
Hope this helps.
Update 1 (from comments)
by reference to namespace
@using Stackoverflow
you do not need to include the static , but when you call it, you will have to refer to the actual class in the namespace, and pass ' this ' to the function.
@SectionExtensions.RenderSection(this, "extra", @<span>This is the default!</span>)
Update 2
There is an error in the razor that does not allow you to call delegates of templates Func <dynamic, object> e = @<span>@item</span>; inside section. See https://github.com/aspnet/Razor/issues/672
Current workaround:
public static class SectionExtensions { public static IHtmlContent RenderSection(this RazorPage page, [RazorSection] string name, IHtmlContent defaultContents) { return page.IsSectionDefined(name) ? page.RenderSection(name) : defaultContents; } }
and then the razor page:
section test { @this.RenderSection("extra", new HtmlString("<span>this is the default!</span>")); }
Nick de beer
source share