I have a project using ASP.NET Boilerplate. I want to add more functionality by using jQuery.
I try to write a simple code such as (below) to the end of a page (such as
Here is the process to proper execution; check @RenderSection
and @section
in below files
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<!-- .removed.for.brevity. -->
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<!-- .removed.nav.bar.for.brevity. -->
<div class="container body-content">
@RenderBody()
<hr />
<!-- .removed.footer.for.brevity. -->
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
<!-- .below script section will render from view cshtml. -->
@RenderSection("scripts", required: false)
</body>
</html>
view.cshtml
<!-- All your view html -->
@section Scripts {
<script>
$(function () {
$('body').css('background', 'red');
});
</script>
}
do what the others said, but use
<script>
$(document).ready(function () {
$('body').css('background-color', 'red');
});
</script>
Also aspnet boilerplate does not use bundles or a
@RenderSection("scripts", required: false)
in it's layout.
jquery is linked in the layout, so you must use the layout. The default _ViewStart.cshtml defines the _Layout.cshtml as the layout.
To get the javascript in the scripts section from your cshtml pages (views) to render you must add the
@RenderSection("scripts", required: false)
to the _Layout.cshtml