Oleg Sh
Oleg Sh

Reputation: 9013

Put javascript of PartialView to special place on page

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 :)

Upvotes: 0

Views: 705

Answers (1)

JEV
JEV

Reputation: 2504

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

Upvotes: 1

Related Questions