0

I have the following page:

Page.cshtml:

<some html>
        @foreach (var item in Model.OffersOutstanding)
        {
            @Html.Partial("PartialOfferAccept", item.AcceptForm)
        }
</some html>
    <script>
// all js here
</script>
/* end of file */

and PartialView PartialOfferAccept.cshtml:

<some html>...</some html>
<script>
// script, specified for partial view
</script>

in result html it works, but mixed js and html. I want to put all partial view scripts to the end of page. It would be better to do with RenderAction, but RenderAction is allowed only for Layouts. Any way to separate partial view content and put to different places on page. PS. Ability to separate a partial view to 2 partial views don't offer :)

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • Your scripts should all be in the main view (or its layout), not in partial views (you will be rendering the same script multiple times) –  Mar 10 '15 at 11:17
  • but script is generated in partial view, depending on partial data – Oleg Sh Mar 10 '15 at 11:45
  • 3
    Partial views do not support sections, so you don't have any option for custom placement. But in any case, the scripts should be in the main view (and SO is littered with questions as a result of various problems that arise from having scripts in partial views). –  Mar 10 '15 at 12:08

1 Answers1

1

Turns out my below answer is apparently not possible by design. Not sure why it's like this however the following question poses the same issue as you are having, and it links to a Nuget package to enable the below functionality.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Old Answer

You should use the @section helper. On that partial view you need to just do this:

@section Scripts { 

    <script>
        //Partial view code here
    </script>
}

And then on your _Layout.cshtml you should have the following at the bottom of the page

@RenderSection("Scripts", false)

This way you can easily manage and place all your scripts in one place with custom scripts on a per view basis

Community
  • 1
  • 1
JEV
  • 2,494
  • 4
  • 33
  • 47