ohyeah ohyeah - 3 months ago 8
ASP.NET (C#) Question

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. 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?

Answer

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