【发布时间】:2016-06-21 11:45:03
【问题描述】:
我在 layout 上的脚本有问题,所以我去基本的尝试了解 @RenderSection("scripts", 的作用,现在我让它工作了。
但是我可以将 Jquery / Jquery.UI (js/css) 放在布局中,这样我就不必将它放在每个视图上吗?因为我尝试在 Layout 上的 head 标签内放置,但视图没有看到它。
这是我的布局。
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<h1>Test Layout</h1>
<div>
@RenderBody()
</div>
</body>
</html>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
我的观点
@{
ViewBag.Title = "TreeDetails";
Layout = "~/Views/Shared/_LayoutTest.cshtml";
}
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<h2>TEST PAGE</h2>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
<button id="opener">Open Dialog</button>
</body>
</html>
@section scripts {
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
// Your code goes here.
$(document).ready(function () {
console.log("before dialog");
$("#dialog").dialog({ autoOpen: false });
console.log("after dialog");
$("#opener").click(function () {
$("#dialog").dialog("open");
});
})
</script>
}
【问题讨论】:
-
将
@RenderSection(...)移动到关闭</body>标记之前。另请注意,您的 css 文件应位于<head>标签内的单独@RenderSection("styles", required: false)中。而且看起来您在布局中重复使用jquery.js@Scripts.Render("~/bundles/jquery"),并再次将其包含在@section scripts {中 -
@StephenMuecke 所以,如果我在
head中声明所有脚本/css 以用于布局,那么我不需要@Scripts.Render(..)行? -
是的,您仍然应该拥有它们(添加视图特定脚本等)。但它建议
@RenderSection("styles", false)进入<head>和@RenderSection("styles", false)紧接在关闭</body>标记之前(此时您将它们放在文档之外) -
@StephenMuecke 我还是迷路了。你能编辑我的视图/布局并告诉我应该怎么走吗?我发现从视图中删除 jquery 会使事情变得更好,但仍然看起来很奇怪。因为 jquery.ui 仍在视图中。而且我还没有选择样式。
-
你还有其他问题,比如你的视图不应该有
<head>标签等。给我30分钟,然后我会添加答案。
标签: javascript asp.net-mvc layout