布局上的脚本是否可以传播到视图?



我对布局上的脚本有问题,所以我去基本版尝试了解@RenderSection("scripts",在做什么,现在我让它工作。

但是我可以把Jquery/Jquery.UI(js/css)放在布局中,这样我就不必把它放在每个视图上吗?因为我尝试在布局上放入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>
}

您的代码存在一些问题,包括呈现文档外部的脚本、复制脚本(包括脚本部分中的 css 文件)以及在视图中复制<html><head><body>标记。

布局的基本结构应该是

<html>
<head>
<title>@ViewBag.Title</title>
....
// Add style sheets common to all views using this layout
@Styles.Render("~/Content/css")
// Add the place holder for any view specific css files
@RenderSection("styles", required: false)
// Include modernizr
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<h1>Test Layout</h1>
<div>
@RenderBody()
</div>
// Add js files common to all views using this layout
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
// Add the place holder for any view specific js files
@RenderSection("scripts", required: false)
</body>
</html>

和视图

@{
ViewBag.Title = "TreeDetails";
Layout = "~/Views/Shared/_LayoutTest.cshtml";
}
<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>
// View specific style sheets
@section styles {
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
}
// View specific scripts
@section scripts {
// Note: don't repeat jquery-{version}.js
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
console.log("before dialog");
$("#dialog").dialog({ autoOpen: false });
console.log("after dialog");
$("#opener").click(function () {
$("#dialog").dialog("open");
})
</script>
}

注意:在这种情况下,使用$(document).ready(function () {并不是绝对必要的,因为脚本是在结束</body>标签之前呈现的,但如果要将@Scripts.Render(...)@RenderSection("scripts", required: false)移动到布局的<head>标签中,则需要这样做。

最新更新