目前,我已将 jQuery 源文件添加到我的 ASP.NET 项目的 Scripts 文件夹中。在 _Layout.cshtml 页面中,我包含了 ~/Scripts/jquery-2.1.1.min.js。现在,我可以通过这种方式在每个页面上包含 jQuery 代码:
If this page shows a popup I was succesfull.
<script>
$(document).ready(function(){
alert("works!");
});
</script>
但是,我不想在每个 View 中都包含完整的脚本。我更愿意创建一个单独的 JS 文件,将它放在我的脚本文件夹中,然后使用 Razor 包含它。
@{
//Razor Magic inserting Javascript method!
}
If this page shows a popup I was succesfull.
我该怎么做?这是为单个页面包含唯一 Javascript 文件的“正确”方式吗?
最佳答案
您可以将页面特定的 JS 代码放在单独的 JS 文件中,并可以使用以下代码段引用您的特定 View :
1) 您需要将此部分放入您的 _Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-2.1.1.min.js)">
@RenderSection("JavaScript", required: false)
</head>
2) 您需要将@section 添加到要在其中引用您的JS 文件的 View - (_ABCDView.cshtml)
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SampleScript2.js")"></script>
}
注意: @RenderSection,false,表示在使用该母版页的 View 上不需要该部分,并且 View 引擎将忽略您的 View 中没有定义“JavaScript”部分的事实。如果为 true,除非定义了“JavaScript”部分,否则将不会呈现 View 并抛出错误。
一切顺利!
希望对您有所帮助。
谢谢, 斯瓦特语
关于javascript - 是否有将自定义 Javascript 添加到 ASP.NET MVC 5 页面的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25720250/