Does RenderSection() work inside ASP.NET Core's <environment> tag-helper?

grokky picture grokky · Oct 27, 2016 · Viewed 16.3k times · Source

Layout has this:

<!DOCTYPE html>
<html>
<head>
  <environment names="Development">@RenderSection("devCss", required: false)</environment>
  <environment names="Staging,Production">@RenderSection("staproCss", required: false)</environment>
</head>
<body>
  @RenderBody()
  <environment names="Development">@RenderSection("devJs", required: false)</environment>
  <environment names="Staging,Production">@RenderSection("staproJs", required: false)</environment>
</body>
</html>

View has this:

@section devCss { <link rel="stylesheet" href="foo.css" asp-append-version="true" /> }
@section staproCss { <link rel="stylesheet" href="foo.min.css" asp-append-version="true" /> }
@section devJs {}
@section staproJs {}

<h1>hello</h1>

When RenderSection() is outside the <environment> tag, everything works.

When inside, as in above example, it fails with the unhelpful error of InvalidOperationException: The following sections have been defined but have not been rendered by the page at '_Layout.cshtml': 'staproCss, staproJs'. To ignore an unrendered section call IgnoreSection("sectionName").

That obviously makes no sense, as all sections were defined. And it complained about some, and not the others.

Does the <environment> tag-helper allow RenderSection() within it?

Answer

Said Roohullah Allem picture Said Roohullah Allem · Jul 2, 2019

Just Add @RenderSection("Scripts", required: false) in end of </body> tag.