Oliver
Oliver

Reputation: 9002

Razor RenderSection within script tags - How to insert script from view into template function

I'm using MVC 3 with the Razor view engine and I would like to inject scripts from multiple views into one centrally defined $(document).ready(); function in the master page.

I have tried the following:

<script type="text/javascript">
    $(document).ready(function () {
      //OnLoad Script load area
      '@RenderSection("DocumentReady", false)'
    });
</script>

In my master view, and then:

@section DocumentReady{
    alert('Document is ready!');
}

In my view, but unsuprisingly, we get compilation errors due to the javascript not being within a <script> tag.

If there are a lot of small view controls that need to run some initialisation script in the $(document).ready() function, it would be nice to keep them all together in a single place.

Is there a way to inject javascript to a master view without the surrounding <script> tags and without affecting compilation?

Upvotes: 45

Views: 97582

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039000

You don't need the single quotes around the RenderSection call in your layout:

<script type="text/javascript">
    $(document).ready(function () {
        @RenderSection("DocumentReady", false)
    });
</script>

and inside the view:

@section DocumentReady {
    alert('');
}

But it will probably be more readable if you have a scripts section in your layout:

@RenderSection("Scripts", false)

and inside the view:

@section Scripts {
    <script type="text/javascript">   
        $(function() {
            alert('');
        });
    </script>
}

Upvotes: 92

Ema.H
Ema.H

Reputation: 2878

For example, in your _layout.cshtml :

@RenderSection("JavaScript", required: false)

And then in your view :

    @section JavaScript
    {
       <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
       <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>

       <script type="text/javascript">console.log("in the js");</script>
    }

Hope that helps

Upvotes: 12

Related Questions