How can you define sections with default content in MVC 6?

I'm currently trying to migrate an ASP.net MVC 5 project to MVC 6.

How do I migrate the following code:

public static class SectionExtensions { public static HelperResult RenderSection(this WebPageBase webPage, [RazorSection] string name, Func<dynamic, HelperResult> defaultContents) { return webPage.IsSectionDefined(name) ? webPage.RenderSection(name) : defaultContents(null); } } 

[RazorSection] is part of the JetBrains.Annotations assembly.

+7
migration extension-methods asp.net-core view asp.net-core-mvc
source share
1 answer

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>")); } 
+6
source share

All Articles