Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 504
Chris Marisic Avatar asked May 12 '11 16:05

Chris Marisic


2 Answers

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.

like image 199
SLaks Avatar answered Oct 20 '22 00:10

SLaks


@JasCav: If a partial needs its own CSS, it has no good way to get it rendered.

If that's the reason for its use, it could very well be by design.

You don't want to have a separate CSS file x partial/helper. Remember, each separate CSS file means a separate request to get it from the server, thus an additional round-trip that affects time to render your page.

Also you don't want to emit direct CSS to the HTML from the partial/helper. Instead you want it to have appropriate hooks you can use to define all the look in your site's CSS file.

You can use the same hooks you have available for CSS to activate custom JavaScript behaviors for the elements involved When JavaScript is enabled.

Finally it may be the case what you need is not a Partial View, but an extra Layout you use for some pages. With that approach you would have:

  • A master Layout that gets set automatically on _ViewStart like you probably has now. This defines the sections like in your sample.
  • A children Layout page. Here you have both the extra html, css, js you need to have for these views. This uses both @RenderBody() and @section SomeSection { } to structure your common extra layout.
  • Some views that point to the children layout, and others that use the default master layout.

How to get extra data to the children Layout is out of the scope of the question, but you have several options. Like having a common base for your entities; using ViewBag or calling Html.RenderAction to get that shared logic related to shared dynamic elements in the layout.

like image 31
eglasius Avatar answered Oct 19 '22 22:10

eglasius