Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery is not available in ASP.NET Core 2.2 Razor view

I created a simple ASP .Net Core (version 2.2) Web Application (non-MVC) in Visual Studio 2017 Community (Version 15.9.6)

By default, jQuery (version 3.3.1) is included in the wwwroot/lib/jquery directory.

I am getting jQuery IntelliSense.

jQuery is referenced in the default /Pages/Shared_Layout.cshtml file correctly.

I added the following code to the default.csthml page:

<script type="text/javascript">
     $(document).ready(function () {
         $("p").click(function () {
             $(this).hide();
         });
     });
</script>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

This simple code does not work by default.

I do not understand why.

Console Error

0x800a1391 - JavaScript runtime error: '$' is undefined

Markup

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <title>@ViewData["Title"] - jQueryTest2</title> 
    <link rel="stylesheet" href="~/css/site.css" /> 
</head> 
<body> 
    <header></header> 
    <div class="container"> 
        <main role="main"> @RenderBody() </main> 
    </div> 
    <footer></footer> 
    <environment exclude="Development"> 
        <script src="cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/>
    </environment>
</body> 
</html> 
like image 687
1 Zero 3 Tech Avatar asked Mar 04 '23 15:03

1 Zero 3 Tech


1 Answers

First add @RenderSection("Scripts", required: false) at the bottom of the body of your Layout.cshtml page.

Then your scripts inside @section Scripts as follows:

@section Scripts{
    <script type="text/javascript">
       $(document).ready(function () {
           $("p").click(function () {
             $(this).hide();
           });
       });
    </script>
}

Hope this will solve your problem!

like image 59
TanvirArjel Avatar answered Mar 08 '23 10:03

TanvirArjel