Nate Nguyen
Nate Nguyen

Reputation: 59

Where to use/put jQuery in ASP MVC .Net Core?

I learned that it is recommended to load jQuery at the end of the page (aka footer)

I am currently experimenting with the Scaffold template from the MVC project. Now, my scenario is that I have a _Layout where jQuery/script/bootstrap are loaded in the footer. Says I have a view called "Index.cshtml" that will use _Layout.cshtml as layout. And inside "Index.cshtml", I am just having something as simple as this:

<script>
$(document).ready(function () {
    $('#test').on('click', function (e) {
        alert("hey");
    });       
});
</script>
<button id="test">test</button>

My questions is:

I want to bind event to the button using jQuery. How can i call $(document).ready... inside "Index.cshtml" so I can achieve this in the most efficient way? (since the jQuery is loaded later on at the footer and I want to write my code in the corresponding page instead of in a shared page like _Layout.cshtml). I was thinking to load jQuery in the view, but that would make it a duplicate load wouldn't it?

Solution

In case anyone ran in the the same question like me, please check out Robert's answer below.

Basically the Scaffold template of ASP MVC .Net Core defined a @Section named "Scripts". Therefore, if we define that Script in our View, it will be loaded into the footer of _Layout right after the scripts for jquery/js are loaded.

Upvotes: 1

Views: 1712

Answers (1)

RobertC
RobertC

Reputation: 590

There are a few ways, but why not give the script section a try?

@section Scripts {
 <script type="text/javascript" src="/scripts/main.js"></script>
}

Source: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-3.0

Or in your case:

@section Scripts {
    <script>
    $(document).ready(function () {
        $('#test').on('click', function (e) {
            alert("hey");
        });       
    });
    </script>
 }

Upvotes: 1

Related Questions