In ASP.NET Core MVC, the recommended way to include scripts is to define a section (usually named "Scripts") in your layout page (e.g., _Layout.cshtml), and then render your scripts from your views or partial views into that section. This ensures all your scripts are loaded at the right place (typically just before </body>), especially when you have multiple views sharing the same layout.
Step 1: Define the Scripts section in your Layout file
Open your layout file, usually _Layout.cshtml (under Views/Shared), and add the section render call near the end, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - My ASP.NET Core App</title>
<link rel="stylesheet" href="~/css/site.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- jQuery CDN -->
</head>
<body>
<div class="container">
@RenderBody()
</div>
@RenderSection("Scripts", required: false)
</body>
</html>
Explanation:
@RenderSection("Scripts", required: false) means your views can optionally define a "Scripts" section.
- The jQuery library is included once here so
$ is available in any view script.
Step 2: Add the "Scripts" section in your view page
At the bottom of your view—for example, Index.cshtml—add a Scripts section:
@section Scripts {
<script>
$(function() {
$('canvas').each(function() {
const overlay = overlayCanvas(this);
enableSigning(overlay);
});
});
</script>
}
This way, the script is included where @RenderSection("Scripts") is called (in your layout), ensuring jQuery loaded before your script runs.
Full example
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - My ASP.NET Core App</title>
<link rel="stylesheet" href="~/css/site.css" />
<!-- jquery loaded once here -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
@RenderBody()
</div>
<!-- Render any page-specific scripts here -->
@RenderSection("Scripts", required: false)
</body>
</html>
Index.cshtml:
@{
ViewData["Title"] = "Home";
}
<h2>Canvas signing</h2>
<canvas width="400" height="200"></canvas>
@section Scripts {
<script>
$(function () {
$('canvas').each(function () {
const overlay = overlayCanvas(this);
enableSigning(overlay);
});
});
</script>
}
Notes:
- Make sure your
overlayCanvas and enableSigning functions are defined and loaded before or inside your view script.
- You can also put common scripts in separate files and include them in the layout or bundle & minify.
- You can use
required: false to make section optional in layout, or true to enforce views must define the section.
If you want me to explain bundling or how to add script files outside of inline scripts, just ask!