32

I created a ASP.NET core template and wrote a jquery script. When I look at the page I see that jquery is loaded into the page, but the script doesn’t run. I looked at the ASP.NET docs page and my layout.cshtml looks the same, so are there extra steps I must take to get jquery working? enter image description here Home page

@{
    ViewData["Title"] = "Home Page";
}
<!-- Page Content-->
<div class="container">
    <div class="row">
        <form method="post" enctype="multipart/form-data">
            <input type="file" id="files" name="files" multiple />
            <input type="button" id="upload" value="Upload Selected Files" />
        </form>
    </div>
</div>
<script>
    $(document).ready(function () {
        alert("Test"); 
    });
</script>

Solution

@section scripts
{
    <script>
        $(document).ready(function() {
            alert("Test");
        });
    </script>
}
AJ_
  • 3,787
  • 10
  • 47
  • 82
  • Do you get any errors in the debug console? – Jamiec Jun 20 '16 at 13:29
  • 1
    Are you loading jQuery before the `$(document).ready` ? – apokryfos Jun 20 '16 at 13:30
  • 1
    Where is your reference for jQuery in relation to that page? Is it above or below that script? – Grizzly Jun 20 '16 at 13:30
  • @BviLLe_Kid Below the page, but that’s why its $(document).ready – AJ_ Jun 20 '16 at 13:32
  • You have attempted to use jquery ($) before loading the library – LDJ Jun 20 '16 at 13:32
  • @Jamiec yeah, $ is not defined – AJ_ Jun 20 '16 at 13:32
  • Either move your script under the place where you are loading jquery or move the loading of jquery above the script mentioned in the question. At any rate, if you're going to use `$` make sure it's defined. – apokryfos Jun 20 '16 at 13:35
  • 4
    Use @section scripts { } See here : http://stackoverflow.com/questions/23327578/what-is-rendersection-in-asp-net-mvc – Mottor Jun 20 '16 at 13:50
  • The Question was flagged, but i solved it by using sections. – AJ_ Jun 20 '16 at 14:13
  • This is a great question literally had to change where I was rendering my section at and this was the question I needed to be asked and I could not figure out how to ask it thanks so much – AlThePal78 Sep 25 '21 at 00:18

6 Answers6

28

I suspect your jquery is loaded after the rest of the page content.

This means that you cannot reference jquery objects as the library has not been initialised yet.

Move the page script after jquery has loaded.

<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
  $(document).ready(function () {
    alert("Test"); 
  });
</script>

For efficiency I recommend you do this in one of two ways:


OPTION 1

Use a master script file that loads after jquery.

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/master.js"></script>

OPTION 2

Use a placeholder template that will always load after jquery but can be initialised on individual pages.

Master _Layout Page

<script src="~/lib/jquery/dist/jquery.js""></script>
@RenderSection("Scripts", required: false)

Content Page

@section Scripts {
  <script>
    $(function () {
      alert("Test"); 
    });
  </script>
}
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
14

FOR CLARIFICATION


If you are referencing jQuery in your _Layout page.. double check to ensure that that reference is at the TOP of your _Layout page because if it is at the bottom, then every other page you have that use the _Layout and has jQuery, it will give you errors such as:

$ is undefined

because you are trying to use jQuery before it is ever defined!

Also, if your are referencing jQuery in your _Layout page then you do not need to reference it again in your pages that use your _Layout style


Make sure that you are loading the reference to jQuery before you start using <scripts>.

Your cshtml should work if you put the reference above your script as so:

<script src="~/Scripts/jquery-1.10.2.js"></script> // or whatever version you are using

// you do not need to use this reference if you are already referencing jQuery in your Layout page

<script>
    $(document).ready(function () {
        alert("Test"); 
    });
</script>
Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • 1
    Why would i load it twice? – AJ_ Jun 20 '16 at 13:34
  • 1
    you don't load it twice... load it once but load it before the page is rendered to the screen... simply move your jQuery reference above your script – Grizzly Jun 20 '16 at 13:36
  • The ASP.NET Core template does this for you in the _Layout.cshtml file. Additionally it uses the environment tag to select a local copy in Dev or a CDN in Staging and Production. – Clint B Jun 20 '16 at 13:37
  • @ClintB I know that, but obviously in the OP's `_Layout` the reference to jQuery is at the bottom of their -Layout page... they simply need to move that reference to top of their `_Layout` page. – Grizzly Jun 20 '16 at 13:39
  • @BviLLE - JavaScript files should be loaded on the bottom of the page to allow the visual elements to load before running scripts that may generate errors. He's making the call inside of $(document).ready which is called after the page loads. Like John said, why would he load it twice? – Clint B Jun 20 '16 at 13:42
  • @ClintB If he is loading the reference in his `_Layout` then the OP does not need to reference jQuery again in his pages that are using his `_Layout` style.. so yes, I get what @John and you are saying about loading twice – Grizzly Jun 20 '16 at 13:46
  • People, there is @section scripts { } which you can use on the page and then is loaded from @RenderSection("scripts", required: false) on the _Layout.cshtml . You do not need to load something – Mottor Jun 20 '16 at 14:10
  • The scripts loaded from the _Layout are loaded last and then the @section scripts {} is the last to load more scripts. If the script is in the cshtml, it needs to be wrapped around with the section scripts {}, or reference JavaScript files to load then. This answer is worked for me https://stackoverflow.com/questions/23327578/what-is-rendersection-in-asp-net-mvc – Stephen Himes Jan 10 '19 at 19:06
4

If you create a new .Net Core 2.2 - Web Application with Razor Pages and try to add a jQuery script in index.cshtml you will get the error Uncaught ReferenceError: $ is not defined. As already mentioned this is because jQuery is loaded after the rest of the page content.

Fix this by navigating to Pages\Shared\_Layout.cshtml and add the scripts section to the html head tag instead. Then it will work:

Example:

Move from below </footer>:

<environment include="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
            asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
            asp-fallback-test="window.jQuery"
            crossorigin="anonymous"
            integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
            asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
            crossorigin="anonymous"
            integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
    </script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>

@RenderSection("Scripts", required: false)

Into <head>, should look like this:

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - JiraApp.Clients.Web</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
              crossorigin="anonymous"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
    </environment>
    <link rel="stylesheet" href="~/css/site.css" />
    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
        </script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
        </script>
    </environment>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @RenderSection("Scripts", required: false)
</head>
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
Ogglas
  • 62,132
  • 37
  • 328
  • 418
0

Thanks to everyone who contributed to these answers. I am new to JavaScript/jQuery and have been trying to get jQuery scripts to work for over two weeks now. I have gotten a few examples to work but, until now, I had no idea why something worked or did not work.

All of the examples I have looked at online show the references to .js files at the bottom of the page. None of the examples explain how the _Layout.cshtml file works in relation to the Razor views in an application. It is so confusing to add the links and script references to the _Layout.cshtml file only to have it not work as expected. Next, I moved the links and references to a header section on the razor page and it still did not work. Now that I have everything organized correctly, it is working and I understand why!!! The key was putting the script inside the @section Scripts {} block. I had seen the call to RenderSectionAsync but did not realize what it was doing. This is how the bottom of my _Layout.cshtml file looks now:

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery/dist/jquery.inputmask.min.js"></script>
<script src="~/lib/jquery/dist/inputmask.binding.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)

I hope many new developers see this post. When it comes to an ASP Net Core application with Razor views, the information provided in this thread is priceless! Again, many thanks to everyone who contributed to the answer.

0

must write below first line in while where you want to execute script. if you write first line in other wile, it is not working.
below example to test JQUERY work or not.

<script>
    $(document).ready(function () {
        alert("Test");
    });
</script>
Khan
  • 151
  • 1
  • 4
0

This is similar to the fullcalendar question posed here on Stackoverflow. I shared the following solution on that question --

This is a good reference for what has been asked here. I downloaded jQuery directly and unarchived it into the wwwroot/lib folder/directory to get going with my project - however as I needed more JS libraries, it seemed that the Nuget option of installing JS libraries into my project really was an impossible path/option.

Consider;

not sure why you would use nuget packages for javascript libraries. your example has not been updated in the last four years, and probably doesn't support .net core projects (may not even work a current version of jQuery). you should be using a javascript repository and package mangers like bower or npm, that manages the dependencies between libraries.

That is from the linked MS Forum. Anyhow, the question can be flagged as a duplicate of the other Fullcalendar question (which was posed two years prior to this one).

Phume
  • 55
  • 11