Razor - insert same section more than once

Viewed 323

In the page:

@section NavLinks {
    some content here...
}

In the layout:

<div class="NavLinks">
    @await RenderSectionAsync("NavLinks", required: false)
</div>
<div id="MainContent">
    @RenderBody()
</div>
<div class="NavLinks">
    @await RenderSectionAsync("NavLinks", required: false)
</div>

And results in:

InvalidOperationException: RenderSectionAsync invocation in '/Pages/Shared/_Layout.cshtml' is invalid. The section 'NavLinks' has already been rendered.
Microsoft.AspNetCore.Mvc.Razor.RazorPage.RenderSectionAsyncCore(string sectionName, bool required)
WebSite.Pages.Shared.Pages_Shared__Layout.<ExecuteAsync>b__14_1() in _Layout.cshtml
+
                    @await RenderSectionAsync("NavLinks", required: false)

Any ideas how to make it work?

2 Answers

I could reproduce the problem on my side, it seems that we can't render the same section more than once. As the alternative workaround, I suggest you could try to use the following method to display the content:

  1. Using different section name, code as below:

     <div class="NavLinks">
         @await RenderSectionAsync("Top_NavLinks", required: false)
     </div>
     <div id="MainContent">
         @RenderBody()
     </div>
     <div class="NavLinks">
         @await RenderSectionAsync("Footer_NavLinks", required: false)
     </div>
    

    and define them in Razor Pages view:

     @section Top_NavLinks {
         some content here...
     }
     @section Footer_NavLinks {
         some content here...
     }
    
  2. Using partial view:

     <div class="NavLinks"> 
         <partial name="_NavLinks.cshtml" />
     </div>
     <div class="container">
         <main role="main" class="pb-3">
             @RenderBody()
         </main>
     </div>
     <div class="NavLinks"> 
         <partial name="_NavLinks.cshtml" />
     </div>
    

    Then, add some code in the partial view(_NavLinks.cshtml), like this:

      <ul>
         <li><a href="#">Hyper Link</a></li>
         <li><a href="#">Hyper Link</a></li>
         <li><a href="#">Hyper Link</a></li>
     </ul>
    

    The result like this:

    enter image description here

Finally, for using the same section more than once, I suggest you could try to submit a feedback.

Is the question specific to section OR a piece of Razor code? Instead of RenderSection use Partial tag and put your re-usable code in that Partial View.

Related