有没有一种正确的方法可以将自定义Javascript添加到ASP.NET MVC 5页面中

Is there a correct way to add custom Javascript to an ASP.NET MVC 5 page?

本文关键字:添加 Javascript 自定义 ASP NET 5页 MVC 一种 方法 有没有      更新时间:2023-09-26

目前,我已将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>

但是,我不想在每个视图中都包含完整的脚本。我更喜欢创建一个单独的JS文件,把它放在我的Scripts文件夹中,然后用Razor包含它。

@{ 
    //Razor Magic inserting Javascript method!
 }
If this page shows a popup I was succesfull.

我该怎么做?在单个页面中包含一个唯一的Javascript文件是"正确的"方式吗?

您可以将页面特定的JS代码放在一个单独的JS文件中,并可以使用以下代码引用您的特定视图:

1) 您需要将此部分放在_Layout.cshtml

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

2) 您需要将@部分添加到要引用JS文件的视图中-(_ABCDView.cs.html)

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

注意:@RenderSection为false,表示在使用此母版页的视图中不需要该节,并且视图引擎将忽略在视图中没有定义"JavaScript"节的事实。如果为true,则除非定义了"JavaScript"部分,否则视图将不会呈现,并将引发错误。

你很适合去!

希望这对你有帮助。

谢谢,Swati

在MVC中解决问题的最佳方法是将Bundles称为Bundling and Minification

点击此处查看更多信息:-http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification