Adding Script files to an MVC4 application and _ Layout.cshtml confusion

26,510

Solution 1

Just want to add bit to the above answers. If wish to add custom JavaScript to a specific view, and you are using the standard MVC4 template that comes from Microsoft, all of the bundled jQuery and BootStrap javascripts are positioned in the bottom of the page. The reason for this is so that these will load after the DOM ( document object model, basically the page with all of html content) is rendered in the browser.

Look at _Layout.cshtml. Notice that bottom part of the page has a line dedicated to rendering a section called "scripts"

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

So what you need to do is add new section in your view .cshtml page. Name it "scripts". You should add this after the initial ViewBag section.

ExampleView.cshtml:

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

@section scripts{
    <script type="text/javascript">
        //Here is the custom javascript just for this view.
        alert("I will only say hello on view.");    
    </script>
}

When you launch your view, this custom JavaScript will only be run only on this view.

Hope this helps.

Solution 2

Ok. This is my first answer and I am really syked about this but it took me a long time to figure this out. I hope this helps everyone.

Best way around this problem is to first place all your js files in the Script folder in your MVC application in the Solution Explorer. Be sure they end in .js and are not in other sub folders of the Scripts folder.

Once you have added that file to your Scripts folder go up to your App_Start folder. You will see the class file BundleConfig.cs open up that file. This is where you will be adding your js files to your bundle

the code should look something like this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/Your.JavaScript.File.js"));

Now go into your _Layout.cshtml page in the views folder. Note that you can also add script tags here but what I am showing is if you wish to link a js file.

Above the closing body tag add this code.

@Scripts.Render("~/bundles/jquery")
</body>
</html>

You can add several js files to the bundle and call them all with this single line of code. Go ahead and run the program and you should be solid. Thanks guys Please let me know if this works for you.

Solution 3

If you attached script files to your _Layout.cshtml page so it means all of your views source contains those script files whether any particular view need or not need them. Actually all scripts which you attached in _Layout.cshtml page goes to every view. But if you attached script files particularly in your view so it means those files are attached with only to that view.

Here you are doing a little mistake. Remove your script files from _Layout.cshtml page and try this:

In _Layout.cshtml:

<head>
@RenderSection("myStyles", false);             // section (for css) which layout fetch from view
@RenderSection("myScripts", false);            // section (for jscript) which layout fetch from view
</head>

In your view:

@section myStyles{
<link rel='stylesheet' href='~/Content/fullcalendar.css'>
}

@section myScripts{

<script type="text/javascript" src="/Scripts/fullcalendar.js"></script>
<script type="text/javascript" src="/Scripts/moment.js"></script>

<script type="text/javascript">
    $(document).ready(function () {

        $('#calendar').fullCalendar({
            header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month, agendaWeek, agendaDay'
        },
        defaultView: 'month',
        firstDay: 1,
        editable: true,
        selectable: true,
        slotMinutes: 60
    });
});
</script>

}

<body>
//do whatever you want
</body>
Share:
26,510
Rookasaur
Author by

Rookasaur

~

Updated on July 25, 2022

Comments

  • Rookasaur
    Rookasaur almost 2 years

    This may be a case that I am remembering this wrong, but...

    I am creating an MVC4 application and in the index page I am looking to add two .js files:

        <script type="text/javascript" src="~/Scripts/fullcalendar.js"></script>
        <script type="text/javascript" src="~/Scripts/moment.js"></script>
    

    This adds the files, but does nothing with them. The only time I get the desired result is when I also add the files to _Layout.cshtml.

    I'm sure in past projects I could add .js files to a page and it would work great, why is it that when starting a project from scratch I need to put everything in the _Layout.cshtml file? Am I doing something wrong?

    Edit: The only code in the index.cshtml file is:

    <link rel='stylesheet' href='~/Content/fullcalendar.css'>
    <script type="text/javascript" src="/Scripts/fullcalendar.js"></script>
    <script type="text/javascript" src="/Scripts/moment.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
    
            $('#calendar').fullCalendar({
                header: {
                left: 'prev, next today',
                center: 'title',
                right: 'month, agendaWeek, agendaDay'
            },
            defaultView: 'month',
            firstDay: 1,
            editable: true,
            selectable: true,
            slotMinutes: 60
        });
    });
    </script>
    <body>
        <div id='calendar'></div>
    </body>
    

    Which renders fine when the scripts are also in `_Layout.cshtml' but doesn't when they are not.