I am working on this ASP.NET MVC project where I am trying to add a Layout to my View. I have some .js files in my Scripts folder in the project, which I want to load in my View so that the components, such as DatePicker, Validation can work. However, by adding the Layout to the View, I see that I am getting the following error Uncaught ReferenceError: $ is not defined.
I understand this as, jQuery is not available for the View. But, I have the jQuery file in the Scripts folder. When I remove the Layout and add references to the scripts in the View directly, in <script src="~/Scripts/jquery-3.4.1.min.js"></script> way, I am not getting the error, and the View is performing correctly with the necessary functionalities.
Code snippets:
Create.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<form method="post" action="~/Controller/Create" id="myForm">
...
</form>
</div>
<script type="text/javascript">
$.validator.setDefaults({ ignore: ":hidden:not(select)" })
$(document).ready(function(){
$('form').validate({
...
});
});
</script>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application Name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
</footer>
</div>
@RenderSection("Scripts", false)
</body>
</html>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
Scripts folder:
