MVC 5 _Layout Ext Javascript Files Loading?

I'm asking this question because I find other examples where each script reference is placed on the actual view where it's used. It would be more centralized to call all external js files in the _Layout if it works well.

Q. Can I also load all my javascript files in the _Layout as well?

    @Scripts.Render("~/bundles/jquery")
     <script  src="~/Scripts/Custom/tablesorter.js"></script>
WorknHardrAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
The _Layout.cshtml is basically the master page of MVC. Whatever you would like to show up in every page of your application you can put in the _Layout file. If a script applies only to one page, then it might not be worth it to put in the _Layout file and have it show up on ever page.

Also, you'll notice in the _Layout file there is a RenderSection call that mentions "scripts". Anywhere in your other pages where you add a section:

e.g.

@section scripts
{
    <script>
        // script code
    </script>
}

Open in new window


...the Framework will take that script section and render it at the location within the output HTML where that RenderSection call is located. This means you can keep your scripts logically located within your project--meaning if they only apply to one page, then you can keep them on that page--but still have them show up in the rendered HTML in a specific location. This really helps when you have scripts that make modifications to the DOM for elements that may not have been rendered yet by the browser (by the time the script is executed).
0
WorknHardrAuthor Commented:
Okay, here's a post concerning my questions which agrees with your suggestion. I don't understand the 'MyScripts' part of it.

Q. Where is @RenderSection("MyScripts", required: false) referenced in the example?
0
WorknHardrAuthor Commented:
Seems to me it would be more like this:

[BundleConfig.cs]
    bundles.Add(new ScriptBundle("~/bundles/campaign").Include(
                    "~/Scripts/Custom/Campaign.js",
                    "~/Scripts/Custom/Campaign-UI.js"));

[_Layout]
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/campaign")
    @RenderSection("scripts", required: false)
</body>

[View]
   @section Scripts {
    @Scripts.Render("~/bundles/campaign")
}
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

käµfm³d 👽Commented:
If you look at the comments in the accepted answer, you will see that the "MyScripts" is really redundant. There's nothing technically wrong with creating the new section, but in actuality that is the whole purpose for the "scripts" section. But, if you were to keep "MyScripts", then in your your other .cshtml files you would have what Jasen presented in his 2nd snippet; the 1st snippet would appear in _Layout.cshtml.
0
käµfm³d 👽Commented:
RE: Your last post...

The code in the view is wrong. You don't call Render there, you call it in the _Layout, as you've already done. In the view you put whatever javascript code you want to actually execute. Think about it like this:  @Scripts.Render("~/bundles/jquery") includes JQuery in your page; @section Scripts adds the actual JQuery that you want to use to modify your page.
0
käµfm³d 👽Commented:
Here's a simple example:

Layout
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                </ul>
            </div>
        </div>
    </div>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @RenderSection("scripts", true);
</body>
</html>

Open in new window


View
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div id="divToHide">Hide Me</div>
<button type="button" id="theButton">Click</button>

@section scripts
{
    <script>
        $(document).ready(function () {
            $('#theButton').click(function () {
                $('#divToHide').slideToggle();
            });
        });
    </script>
}

Open in new window


In my view you can see that I've added some code to set what happens when I click the button. Even though I've added this code to my Index.cshtml file, because I wrapped the script code in a the @section scripts block, MVC will render that script within the output HTML wherever the @RenderSection("scripts") appears, which in my case is in the _Layout.cshml file.

The same thing would happen with a bundle. You cannot use JQuery without referencing the JQuery library in your page. That's what the bundle is doing. You don't have to RenderSection the JQuery stuff because the bundle will take care of doing that. However, any JQuery that you actually want to invoke--like what I did just above--needs to appear in your page somehow. You can either place it directly in your page (without wrapping it in a @section scripts block), or you can wrap it in a @section scripts block. The only difference between the two is where the script ends up in the HTML that is sent to the browser.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
käµfm³d 👽Commented:
In the HTML that arrives at the browser:

Screenshot
If I don't use the @section scripts:

View
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div id="divToHide">Hide Me</div>
<button type="button" id="theButton">Click</button>

<script>
    $(document).ready(function () {
        $('#theButton').click(function () {
            $('#divToHide').slideToggle();
        });
    });
</script>

@section scripts {}

Open in new window


Screenshot
0
WorknHardrAuthor Commented:
Gotcha, I'm used to working with ASP.NET Web-forms and all the scripts in the <Head>, so the MVC way is most cool....

Also, I'm trying to achieve calling external .js files needed per view instead of loading all ext .js files in the Head. So far the bundles work. I will not be writing jquery in the @section scripts as you illustrated so nicely. Good Job! Great Info!

Here's what I have working so far.

[BundleConfig.cs]
     bundles.Add(new ScriptBundle("~/bundles/campaign").Include(
                     "~/Scripts/Custom/Campaign.js",
                     "~/Scripts/Custom/Campaign-UI.js"));

 [_Layout]
     @Scripts.Render("~/bundles/jquery")
     @Scripts.Render("~/bundles/jqueryval")
     @Scripts.Render("~/bundles/bootstrap")
     @RenderSection("scripts", required: false)
 </body>

 [View]
    @section Scripts {
     @Scripts.Render("~/bundles/campaign")
 }
0
käµfm³d 👽Commented:
Ah, then that should be fine.
0
WorknHardrAuthor Commented:
You the best, thx :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.