Reputation: 2394
the _layout.cshtml has code lines
@Scripts.Render("~/bundles/jquery")
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
by default they are placed inside the <body>
tags by MVC. But when i leave them in this place some times jquery
does not work. so i have decided to put those three lines in the <head>
block in _layout.cshtml
so the page will put styles and script files in the <head>
as anyone would do with php
or jsp
. Good thing is when i put those files in <head>
all my jquery
started working again. But most MVC books says to place the scripts in the <body>
block.
So where should i put them?
updated post:
here is my bundle file:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
}
here is the layout file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Scripts.Render("~/bundles/modernizr")
@RenderSection("scripts", required: false)
</body>
</html>
Here is the view:
@{
ViewBag.Title = "TestPage";
}
<h2>TestPage</h2>
<input type="submit" name="name" value="Click me" id="btn"/>
<div id="d1"></div>
<script type="text/javascript">
$('#btn').click(function(){
alert('clicked');
});
</script>
here is teh video to show that click does not work
Upvotes: 3
Views: 7378
Reputation: 218722
In your layout file, the script tag to load jQuery library is included at the end of the page. But there is another section called scripts
below that. So in your individual pages ( Ex : Index,View etc..) You should be putting your javascript inside the section scripts
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
And in your views (Ex : Index view)
@section scripts{
<script src="~/Scripts/SomePageSpecificFile.js"></script>
<script>
$(function(){
// Your other js code goes here
});
</script>
}
So when razor render the page it will be
<body>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/SomePageSpecificFile.js"></script>
<script>
$(function(){
// Your other js code goes here
});
</script>
</body>
As long as you execute your page specific javascript which uses jQuery inside the scripts
section ,you should be fine.
Upvotes: 8