MVC中的条件部分

I have a twin Layout setup that renders either the entire page (with navigation) or just the contents depending on whether it was an Ajax request or not. I achieve this like so:

_LayoutRightPanel.cshtml

@{
    Layout = !Request.IsAjaxRequest() ? "~/Views/Shared/_Layout.cshtml" : null;
}

This works fine for most pages, but pages that are requested via Ajax that contains @section{}s dont work (they do when loaded normally). I get the following error:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LayoutRightPanel.cshtml": "scripts".

At the bottom of my _LayoutRightPanel I do the following to render scripts, either forcing the section to render on the main layout or rendering it on the current page if its an ajax request

@if (Request.IsAjaxRequest())
{
    RenderSection("scripts", false);
}
else{
    @section scripts{
        @RenderSection("scripts", false)
    }
}
@section scripts{
    @RenderSection("scripts", false)
}

Why are you rendering the scripts section inside of the scripts section? I don't see how that can end in any way but errors or infinite recursion (which ends in an error).

Edit This is incorrect. See my update below.

RenderSection() should be used on the _Layout page (or any page that is wrapped around the current view). This is the target location (where you want the section to end up)

@section scripts{} should be used on your (Partial)View. This is the source location (where you define the section's contents).

Having both references to the same section on the same page defeats the purpose of why you should be using sections in the first place (to pass certain HTML parts to other, wrapping views (e.g. _Layout.cshtml))

Slight update
To directly answer your question, I think the error is thrown because the RenderSection call that's inside of the @section cannot find any section called "scripts" because it has not yet been defined (you're in the process of defining it).

Update

According to this SO question, duplicate names should not be an issue (so you can disregard my comment below).

However, the root cause of the issue (in that question) was that the script sections weren't chained (i.e. you can't render the section 2 layout pages up, it has to be in the specific Layout page of your view (and then keep chaining it upwards to the next Layout page).

Can you confirm that to be set up as intended?

Maybe offtopic, but is there any added value to passing the scripts section to the upper Layout page? Since you're going to render the section either way, should it not work if you always place it in the _LayoutRightPanel page?