38

I am working with MVC v4.
I have a '_BootstrapLayout' page which defines all the twitter bootstrap etc stuff, A main page which defines the site layout, navbar etc, and site pages which inherit from main page.

_BootstrapLayout.cshtml

_MainPage.cshtml @{ Layout = "~/Views/Shared/_BootstrapLayout.cshtml"; }

Index.cshtml @{Layout = "~/Views/Shared/_MainPage.cshtml";}

So Master Page --> Main Page --> site Page(s)

The _BootstrapLayout page contains a rendersection for scripts

@RenderSection("scripts", required: false)

I want to add a scripts section to the Index.cshtml page, but when I do I get the exception

@section scripts {
    <script type="text/javascript">

        $(document).ready(function () {
...

        });

    </script>
}

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

So I added an empty @section scripts to the _MainPage.cshtml, still the same problem ? Even if I add code to the _MainPage scripts section I still get the same error. It doesn't matter where I put the @section in _MainPage, still get the same error.

If I purposely don't close the section (ie, delete the }) then I get an error which indicates that the section is incorrect, so it's parsing the section in _MainPage.

How can I get @RenderSections for scripts on the site pages to work in this case ?

4

1 に答える 1

42

You'll need to redefine the section in _MainPage.cshtml.

_BootstrapLayout.cshtml

@RenderSection("scripts", false)

_MainPage.cshtml

@section scripts
{
   @RenderSection("scripts", false)
}

Index.cshtml

@section scripts
{
   <script>
     // etc.
   </script>
}
于 2013-01-23T12:27:18.640 に答える