12

In my ASP.NET MVC3 project I have a standard _Layout.cshtml generated by Visual Studio 2010 and after closing my <body> tag, I place a RenderSection:

_Layout.cshtml:

</body>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
@RenderSection("ScriptContent", required: false)
</html>

Then in my Index.cshtml View I have:

@model MyApp.ViewModels.MyViewModel
@{ Html.RenderPartial("MyPartial", Model);  }

If I place the @section ScriptContent in the Index.cshtml it displays correctly. If I place it in my Partial View MyPartial.cshtml:

@model MyApp.ViewModels.MyViewModel

@section ScriptContent {
     <script src="@Url.Content("~/Scripts/Filters.js")" type="text/javascript"></script>    
} 

In my page source I have:

</body>
     <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>    
</html>

Meaning the @section is not executed. What might be the cause? Thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
CiccioMiami
  • 8,028
  • 32
  • 90
  • 151
  • Possible duplicate of [How to render a Section in a Partial View in MVC3?](http://stackoverflow.com/questions/13764936/how-to-render-a-section-in-a-partial-view-in-mvc3) – KyleMit Sep 29 '16 at 17:31

1 Answers1

17

It is not possible to set an @section in the layout from a partial view. As a workaround you could instead call an action which renders the necessary <script> and HTML - although this is not very elegant.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 3
    thansk! Therefore the only possible solution, besides the one you propose, is to move the @section within my View – CiccioMiami Dec 19 '12 at 13:31