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?
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> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With