ASP.NET MVC 3 Razor:在 head 标签中包含 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4311783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:50:56  来源:igfitidea点击:

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

javascriptasp.net-mvcincluderazorasp.net-mvc-3

提问by Stephen Patten

I'm trying to figure out the proper Razor syntax to get a JavaScript file for a particular *.cshtml to be in the head tag along with all the other include files that are defined in _Layout.cshtml.

我试图找出正确的 Razor 语法,以便将特定 *.cshtml 的 JavaScript 文件与在 _Layout.cshtml 中定义的所有其他包含文件一起放在 head 标记中。

回答by RPM1984

You can use Named Sections.

您可以使用命名部分

_Layout.cshtml

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}