Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 560
Oliver Avatar asked May 07 '11 19:05

Oliver


1 Answers

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> } 
like image 105
Darin Dimitrov Avatar answered Sep 20 '22 15:09

Darin Dimitrov