Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC5 Why is placing @Scripts.Render below @RenderBody standard in _Layout.cshtml

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!

like image 950
Michael Witt Avatar asked May 20 '14 22:05

Michael Witt


1 Answers

@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>**

}
like image 75
Toan Nguyen Avatar answered Oct 17 '22 01:10

Toan Nguyen