MVC 4 [_Layout.cshtml] - 在页面脚本启动之前添加所有脚本文件

Red*_*ddy 1 c# asp.net asp.net-mvc jquery asp.net-mvc-4

Visual Studio中的ASP.NET**项目.

<script>在_Layout.cshtml文件中包含了所有文件,其中包括底部的所有外部脚本文件...但是在所有视图中同时(例如:AboutUs,ContactUs,Products等...),我有页面相关的脚本在页面的底部.

当我呈现页面时,我收到脚本错误,因为页面脚本在jQuery /其他插件之前运行.

我试图将所有插件脚本放在head部分,但我不认为这是个好主意......

现在我的问题是:

虽然我在每个视图中都有页面级脚本,但如何在页面级第一个<script>标记之前放置_Layout.cshtml中的所有外部插件脚本?

代码呈现后的下面的参考图像...

在此输入图像描述

使用_Layout.cshtml如下文件..

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>@ViewBag.Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    <link rel="stylesheet" href="@Url.Content("~/Content/ui-bootstrap.css")">
    <link rel="stylesheet" href="@Url.Content("~/Content/themes/base/ui-theme.css")">
    <link rel="stylesheet" href="@Url.Content("~/Content/master.css")">
</head>
<body>

    <header>
        <h3>Header 1</h3>
    </header>

    <div id="body">
        @RenderBody()
    </div>

    <footer>
        &copy; copyright
    </footer>

    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>
    <script src="@Url.Content("~/Scripts/clients-init.js")"></script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

和我的AboutUs.cshtml页面如下......

@{
ViewBag.Title = "About";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<section>
    <h2>About us</h2>
    <p>Lorem ipsum dolar sit amet...</p>
    <div class="showHide hide">Hello World!</div>
</section>

<script>
    $(document).ready(function () {
        // Page related script
    });
</script>
Run Code Online (Sandbox Code Playgroud)

Cod*_*und 7

您可以使用为脚本定义部分@RenderSection.

首先修改你_Layout.cshtml的看起来像下面的代码.请注意我放在@RenderSection所有插件脚本文件之后.

<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")"></script>
<script src="@Url.Content("~/Scripts/clients-init.js")"></script>
@RenderSection("scripts", required: false)
Run Code Online (Sandbox Code Playgroud)

然后,在您的About.cshtml文件中,您可以使用@section指令定义一个部分,如下面的代码:

@section Scripts {
    <script>
        $(document).ready(function () {
            // Page related script
        });
    </script>
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,所有Layout.cshml用作布局的视图都会将其脚本渲染到所有插件脚本之后的scripts部分中Layout.cshtml.

要了解有关使用Razor的布局和部分的更多信息,您可以阅读Scott Guthrie的链接.