@RenderSection at Razor pages

2019-08-17 14:23发布

问题:

I try to use the @RenderSection in my website which built with Razor script. I got error when use it with the .cshtml files. It also didn't appear in the IntelliSense at VS.

Now, I just realized that if I remove the @page from the .cshtml file then the error gone and also the IntelliSense offer me the @RenderSection

And my question is: why?

It says in the Microsoft documentation / tutorial that with the new ASP.NET Core Razor scripts:

"@page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs."

So I'm a little bit confused. What's the right way to include html (partial views - like main menu, etc.) in a .cshtml file with the new Razor Pages in ASP.NET Core ?

Thanks.

回答1:

I have work around on this and found when you use @RenderSection in child page than it should be inside any section of its parent page(i.e. _layout.cshtml)

Here your _layout.cshtml should be like,

<!DOCTYPE html>
<html>
  <head>
    <title>@ViewBag.Title</title>
  </head>
<body>
  @RenderSection("MenuContent", false) 
  @RenderBody()
</body>
</html>

Your child page should like,

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
}
@section MenuContent {
  @RenderSection("MenuContent", false)
}

And your nested child page should like,

@section MenuContent
{
    <!-- content -->
}


标签: c# asp.net razor