Although you already have an answer, I would suggest that you rethink the whole concept.
What you are doing here is a combination of a common layout with certain views. These views may change in the future, requiring you to change the layout, there may be more and more, or some of them will be deleted. Thus, your approach violates the principle of shared responsibility: most have several reasons for changing _layout.cshtml.
How about pasting @section SomeSection { <h1>markup</h1> } in views that require such extra code, and rendering it in the layout using @RenderSection("SomeSection") , possibly also with @if(IsSectionDefined("SomeSection")) in the place where you want?
source share