Question

I have a pretty intensive call to a Child Action, with a massive amount of c# code simply called in a few views by:

@Html.RenderPartial("mychildAction")

Now I need to load some javascript file whenever this action is called. I can not put the tags inline (inside the view) because Jquery (and other JS libraries) aren't loaded until the end of the html page.

The (master) _layout should be aware that this ChildAction was called. But it isn't because a Child Action gets a new HttpContext.

The only solution I came up with, is to switch to a partial (including a big chunk of c# code into the partial and add a few strings to some custom object kept in the HttpContext.Current.Items and make my _Layout act appropriatly). But doing so would mean I have no output caching on this ChildAction and I throw in bad practices like code in partials.

What is the best way to handle this scenario?

Was it helpful?

Solution

You can access the HttpContext from the calling action using

Html.ViewContext.ParentActionViewContext

So one could add something to the "Items" collection there, this approach could solve this particuliar issue, but I still wonder if it's the best approach.

OTHER TIPS

The View is responsible for rendering scripts and since the view knows when to render the partial view, it knows when to render the scripts for it.

In your layout you might find this:

@RenderSection("scripts", required: false)

The view can load scripts there like this:

@section Scripts
{
    @Scripts.Render("~/bundles/SomeBundle")
}

This allows the calling view to render scripts.

What is not possible is to render scripts from a partial view or a sub-view.

You might find some workarounds on how to render scripts from a partial view, but in general is the responsibility of the view to know which scripts to load.

edit

Some of the workarounds I've seen are here.

I agree with @Odys

_Layout.cshtml

@RenderSection("scripts", required: false)

ChildView

@{
    Layout = "~/Views/Share/_Layout.cshtml"
}
@section scripts
{
    <script></script>
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top