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

喜夏-厌秋 提交于 2021-02-07 12:16:30

问题


At the moment, I have added the jQuery source file to my ASP.NET project's Scripts folder. In the _Layout.cshtml page, I have included ~/Scripts/jquery-2.1.1.min.js. Right now, I can include jQuery code on every page I make this way:

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.

@{ 
    //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?


回答1:


Best and elegent way to solve your problem in MVC is making Bundles Known as Bundling and Minification.

See more here :- http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification




回答2:


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:

1) You need to put this section in your _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)

@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. If true, the view won't render and an error will be thrown unless the "JavaScript" section has been defined.

And you are good to go!

Hope this will help you.

Thanks, Swati



来源:https://stackoverflow.com/questions/25720250/is-there-a-correct-way-to-add-custom-javascript-to-an-asp-net-mvc-5-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!