MVC3 Layout Page, View, RenderPartial and getting script files into the Header (from the partial view)

Chris Marisic picture Chris Marisic · May 12, 2011 · Viewed 9.9k times · Source

So I have a Layout page

<head>
    @RenderSection("HeaderLast", required: false)
</head>

A view

@section HeaderLast
{
    <script src="@Url.Content("~/Scripts/knockout-1.2.0.js")"
                            type="text/javascript"></script>
}

<div id="profile-tab">
        @{ Html.RenderPartial("_userProfile"); }
</div>

And a Partial view

@section HeaderLast
{
    <script type="text/javascript">
        alert('test');
    </script>
}

<div......

I figured it couldn't be that simple. Is there a proper way to do this out of box or will this always require some kind of mediator and passing stuff around ViewData to manually make the content bubble up to the layout page?

Bounty started: The bounty will be rewarded to the best solution provided for this short coming. Should no answers be provided I will award it to @SLaks for originally answering this question.

Answer

SLaks picture SLaks · May 12, 2011

You cannot define sections in partial views.

Instead, you can put the Javascript in ViewBag, then emit any Javascript found in ViewBag in the layout page.