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

20,055

Solution 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

Solution 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

Share:
20,055
yesman
Author by

yesman

(my about me is currently blank) click here to edit!

Updated on July 31, 2022

Comments

  • yesman
    yesman almost 2 years

    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?