?
Solved

MVC 5 _Layout Ext Javascript Files Loading?

Posted on 2014-08-09
10
Medium Priority
?
1,854 Views
Last Modified: 2014-08-09
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>
0
Comment
Question by:WorknHardr
  • 6
  • 4
10 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40250785
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
 

Author Comment

by:WorknHardr
ID: 40250872
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
 

Author Comment

by:WorknHardr
ID: 40250884
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40250891
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40250894
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
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1160 total points
ID: 40250900
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40250902
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
 

Author Comment

by:WorknHardr
ID: 40250918
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40250921
Ah, then that should be fine.
0
 

Author Closing Comment

by:WorknHardr
ID: 40250951
You the best, thx :)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month15 days, 12 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question