7

My code compiles and runs without errors; however, it doesn't render as I expected.

The Theory:

I want to use multiple layout pages.

The "base" layout should only include the style and javascript files that are being used by the solution.

The other layout should have the html content or wrappers. This layout seems superfluous currently, but my superior assures me it will lead to future greatness. Such as having multiple headers or the ability to not have headers or footers on certain pages. The main things is to have multiple ContentLayouts but one common BaseLayout

The Code:

_BaseLayout

<html>
   <head>
       <link href="@Url.Content("~/Content/css/main.css")" rel="stylesheet" type="text/css" />
       <script type="text/javascript" src="@Url.Content("~/Scripts/common.js")"></script>
       @RenderSection("JavaScript", false)
       @RenderSection("Css", false)
   </head>
   <body>
       @RenderBody()
   </body>
</html>

_ContentLayout

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

 @RenderSection("JavaScript", false)
 @RenderSection("Css", false)

 <div class="page">
     <section class="wrapper">
       @RenderBody()
     </section>
 </div>

View.cshtml

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

 @section JavaScript
 {
      <script type="text/javascript">
    (function ($) {
        $(function () {
            //do stuff;
        });
    } (jQuery));
</script>
 }

 <div>
      //html content
 </div>

Like I stated earlier this works. The problem is when I view the page source the script from the view is rendered in the _ContentLayout and thus falls outside of the designated script area. Can I "kick" the script code to the next layout? This would allow all the script code to be in the same area.

4

1 回答 1

6

你应该发展关于@RenderSection()行为的观点。

每个都@RenderSection()呈现它的后代@section SectionName { }。因此,您需要按以下顺序更改视图:

_BaseLayout.cshtml - 保持原样。

_ContentLayout.cshtml

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

@section JavaScript {
    @RenderSection("JavaScriptToHead", false)
}

@section Css {
    @RenderSection("CssToHead", false)
}

<div class="page">
    <section class="wrapper">
        @RenderBody()
    </section>

最后是 View.cshtml

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

@section JavaScriptToHead {
    //JS stuff
}

@section CssToHead {
   //Css stuff
}

<div>
    //html content
</div>
于 2012-06-27T04:29:03.640 回答