将 JavaScript 添加到 _Layout 页面中的 RenderSection()

Adding JavaScript to RenderSection() in _Layout Page

我确定这个问题一定已经在 Whosebug 上的某个地方被问到并得到了回答,但我已经搜索了又搜索,但我还是找不到。如果社区可能提供任何帮助,我将不胜感激。

我有一个我很满意的表格,但我想通过触摸 JavaScript 来改进它。 JS 与我的应用程序的任何其他页面都不相关,因此我不想将它添加到我的 _Layout 页面。

在我的 _Layout.cshtml 页面的头部元素中,我有:

@RenderSection("head", required: false)

所以,我的页面需要一行代码(我们称之为 page.cshtml),它将在我最终 HTML 的 head 部分添加一个 JS 块(包括脚本标签) .本质上,我认为我需要向 RenderSection 对象发送一段文本。有人能告诉我 page.cshtml 的正确语法吗?

为什么要在head部分专门添加脚本? MVC 默认 _Layout 页面有 @RenderSection("scripts", required: false) 部分。因此,如果您需要在视图 page.cshtml(使用 _Layout)上加载脚本,您应该放置一个代码:

@section scripts {
    <script type="text/javascript">
       //your script
    </script>
}

当 Razor 呈现您的页面时,它会将此脚本添加到部分。

无论如何,如果您想将 sctipt 添加到这个特定的头部部分,可以用相同的方式完成:

@section head {
    //other code that should be in head
    <script type="text/javascript">
       //your script
    </script>
}