1

I used this answer to delay rendering of scripts in partials/editors: https://stackoverflow.com/a/14127332/1612788

This relies on enclosing the desired scripts in a

@using (Html.BeginScripts())
{
    <script>
        var foo = "Bar";
    </script>
}

This works great when the partial is loaded synchronously with the rest of the page. However, when the partial is called from an ajax request, it doesn't render the script in the response.

Is there a way that I can tell it to use Html.BeginScripts when it's a synchronous request, and ignore Html.BeginScripts when it's an asynchronous request? In other words, I just want to write the script out to the response as normal when the partial is requested by ajax.

I could probably do something like:

@if (Request.IsAjaxRequest())
{
    <script>
        var copy = "Bar";
    </script>
}
else
{
    using (Html.BeginScripts())
    {
        <script>
            var copy = "Bar";
        </script>
    }
}

But is there a way this can be done without having two copies of the script in the source?

Community
  • 1
  • 1
Tevis
  • 729
  • 1
  • 12
  • 27
  • I am not 100% sure of your aim, but the example below worked for what I think you have in mind. Let me know if it is not right for you as it can be tweaked :) – iCollect.it Ltd May 06 '15 at 20:25
  • Actually it's a little off. The difference isn't between whether I'm rendering the partial as a partial or as a full with layout, but rather whether I'm rendering the partial synchronously (at the same time as a full with layout) or asynchronously (after the full view has already been rendered, and I'm just injecting the partial after the fact via ajax). I *do* want the script section to be output along with the html in the event that it is being requested via Ajax – Tevis May 07 '15 at 19:39
  • I understand your problem, struggling with same issue. At the moment referencing scripts in the instead of at the end of body is the single solution I came so far. If you have found another solution please share. – Cristian E. Jul 22 '16 at 09:43

1 Answers1

0

Just define a scripts section in the view and put your script in that.

@section Scripts {

    <script>
        var copy = "Bar";
    </script>
}

If the view is rendered in a layout with render section,

e.g. in your layout file:

@RenderSection("scripts", required: false)

it will appear, if it is rendered as a partial view it will not.

The other thing I do is set the layout via a ViewBag setting, so that the controller decides whether to render full as a full or partial view.

Each view contains this code at the top:

Layout = ViewBag.Layout

In the controller actions you do your check:

if (!Request.IsAjaxRequest())
{
    ViewBag.Layout = MyLayoutNameHere;
}
return PartialView();

You always then use PartialView and the presense of Layout = decides whether to render as a full view.

I wound up putting this code in a base controller for convenience.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202