简体   繁体   English

有没有正确的方法将自定义Javascript添加到ASP.NET MVC 5页面?

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

At the moment, I have added the jQuery source file to my ASP.NET project's Scripts folder. 目前,我已将jQuery源文件添加到我的ASP.NET项目的Scripts文件夹中。 In the _Layout.cshtml page, I have included ~/Scripts/jquery-2.1.1.min.js. 在_Layout.cshtml页面中,我包含了〜/ Scripts / jquery-2.1.1.min.js。 Right now, I can include jQuery code on every page I make this way: 现在,我可以在每个页面上包含jQuery代码:

If this page shows a popup I was succesfull.

<script>
$(document).ready(function(){
alert("works!");
});
</script>

However, I don't want to include a full script in every view. 但是,我不想在每个视图中都包含完整的脚本。 I would prefer to create a seperate JS file, put it in my Scripts folder, and then include it using Razor. 我更喜欢创建一个单独的JS文件,将它放在我的Scripts文件夹中,然后使用Razor包含它。

@{ 
    //Razor Magic inserting Javascript method!
 }

If this page shows a popup I was succesfull.

How do I do this? 我该怎么做呢? And is it the "correct" way to include a unique Javascript file for a single page? 是否是为单个页面包含唯一Javascript文件的“正确”方法?

You can put your page specific JS code in a separate JS file and can refer to your specific Views using the following piece of Code: 您可以将特定于页面的JS代码放在单独的JS文件中,并使用以下代码引用您的特定视图:

1) You need to put this section in your _Layout.cshtml 1)您需要将此部分放在_Layout.cshtml中

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

2) You need to add @section to the View in which you want to refer your JS file - (_ABCDView.cshtml) 2)您需要将@section添加到要在其中引用JS文件的视图中 - (_ABCDView.cshtml)

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

}

NOTE: @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will ignore the fact that there is no "JavaScript" section defined in your view. 注意: @ RenderSection,false,表示在使用此母版页的视图上不需要该部分,并且视图引擎将忽略视图中未定义“JavaScript”部分的事实。 If true, the view won't render and an error will be thrown unless the "JavaScript" section has been defined. 如果为true,则视图将不会呈现,并且除非已定义“JavaScript”部分,否则将引发错误。

And you are good to go! 你很高兴去!

Hope this will help you. 希望这会帮助你。

Thanks, Swati 谢谢,斯瓦蒂

Best and elegent way to solve your problem in MVC is making Bundles Known as Bundling and Minification . 在MVC中解决问题的最佳和最好的方法是将Bundles称为Bundling and Minification

See more here :- http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification 在这里查看更多: - http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM