How to use jquery in ASP.NET Core

I created a basic ASP.NET template and wrote a jquery script. When I look at the page, I see that jquery loads on the page, but the script does not run. I looked at the ASP.NET docs page and my layout.cshtml looks the same, so there are additional steps that I have to take to get jquery to work? enter image description here Main 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> 

Decision

 @section scripts { <script> $(document).ready(function() { alert("Test"); }); </script> } 
+8
jquery c # asp.net-mvc asp.net-core
source share
2 answers

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

This means that you cannot reference jquery objects since the library has not yet been initialized.

Move the script page after loading jquery.

 <script type="text/javascript" src="/Scripts/jquery-2.2.4.js"></script> <script> $(document).ready(function () { alert("Test"); }); </script> 

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


OPTION 1

Use the main script file that loads after jquery.

 <script type="text/javascript" src="/Scripts/jquery-2.2.4.js"></script> <script type="text/javascript" src="/Scripts/Master.js"></script> 

OPTION 2

Use a placeholder that will always load after jquery, but can be initialized on separate pages.

Master page

 <script type="text/javascript" src="/Scripts/jquery-2.2.4.js"></script> <asp:ContentPlaceHolder ID="RootScripts" runat="Server"/> 

Content Page

 <asp:Content ID="PageScripts" ContentPlaceHolderID="RootScripts" runat="Server"> <script> $(document).ready(function () { alert("Test"); }); </script> </asp:Content> 
+4
source share

FOR DETERMINING


If you link to jQuery on the _Layout page .. double check that this link is on the TOP page of your _Layout page, because if it is at the bottom, then every other page that uses _Layout and has jQuery will give you errors like :

$ undefined

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

Also, if you link to jQuery on the _Layout page, you do not need to link to it again on your pages that use the _Layout style


Before you start using <scripts> make sure you download the jQuery link.

Your cshtml should work if you placed the link above your script as follows:

 <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> 
+2
source share

All Articles