When I generate a MVC5 app, the _Layout.cshtml
has the @Scripts.Render
at the end of the file after the @RenderBody()
. If I add a .js
into my index.cshtml
that uses jquery, I get the dreaded "$
is undefined" error.
The only way I know to fix this is to move the @Scripts.Render
to the <head>
section.
What is the correct approach?
Thanks in advance!
@Scripts.Render
should be at the bottom of the page. Otherwise, you will have risks of accessing page elements which haven't been loaded at the time the scripts run.
EDIT:
If you want to include your custom scripts files, there are two ways of doing that:
1. In the BundleConfig.cs, add a new bundle for your scripts
*bundles.Add(new ScriptBundle("~/bundles/UserScripts").Include("~/Scripts/MyScripts.js"));*
Next, in the _Layout.cshtml, render the script bundle after jQuery bundle:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@* Render the custom bundles *@
@Scripts.Render("~/bundles/UserScripts")
2. Or add a new script section to your Index.cshtml file:
@section scripts {
<script src="~/Scripts/MyScripts.js"></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