2

In ASP.net MVC 5 We can pass section to layout using

@section AnySection{
  //section code here
}

and render it in Layout by

@RenderSection("AnySection", required: false)

But how can we pass that section again to a partial inside that layout? See the image below for reference how can we pass that section to partial? subheader-v1 is a partial view inside my Layout I have made my Layout with many partial Views. When I try this as mentioned in Image above it gives me this error

The file "~/Views/Shared/partials/_subheader/subheader-v1.cshtml" cannot be requested directly because it calls the "RenderSection" method.'

Ali Jamal
  • 1,383
  • 1
  • 13
  • 20

3 Answers3

4

You don't pass a section to the layout. It is the layout that determines which sections should (or could) be rendered in the view... it also determines where in the view the section should be rendered.

From MS Documentation:

A layout can optionally reference one or more sections, by calling RenderSection. Sections provide a way to organize where certain page elements should be placed.

Sections don't work in partial views and that is by design. You would need to move RenderSection to your layout and the section body to your view. See this question for more information.

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
1

Inside the subheader-v1.cshtml (since the objective is to bring the "CoordinatesSelection" partial into subheader-v1.cshtml) substitute

@RenderSection("Coordinates", required: false) 

FOR

@Html.Partial("CoordinatesSelection", Model)

The code @RenderSection("Coordinates", required: false) was designed to be written directly in the layout to avoid duplicate calls to it!!

1

Two ways:

1. You can migrate from subheader-v1 to layout

layout:

// your subheader-v1 code
@RenderBody()

And you can use RenderSection in the layout

2. You can pass a model to Partial subheader-v1

*layout:

@Html.Partial("partials/_subheader/subheader-v1",RenderSection("Coordinates",false))
@RenderBody()

*subheader-v1:

@model object
.
.
.
<div class="kt-subheader__wrapper">
   @Html.Raw(Model)

*SelectClosetStore

@section Coordinates{
    //your partial code
}

I think the first way is better than the second way.

Masa
  • 32
  • 6