24

I wonder why my js file work when I call it in the view:

@section Scripts {  
<script>   

    function myFunction() {
        alert("Hello1");
    }       

</script>
}

but does not work when I call it:

@section Scripts {

   <script type="text/javascript" src="~/Views/Home/script.js"></script>
   <script>   
         myFunction();
    </script>
}
2
  • These both look like Razor files? Is the top file the _Layout and the second a view using the layout? Commented Jul 15, 2014 at 16:33
  • I'm working in the view. But with "@ section Scripts" I want the script to be placed in the _Layout when run in the browser. Thanks. Commented Jul 15, 2014 at 23:13

4 Answers 4

30

It's because .js files are not accessible in the ~/Views/ folder. You have to enable it.

To enable access to .js files in the Views folder, you can add the following to your Views' folder's web.config directly under the handlers tag:

<add name="JavaScriptHandler"
         path="*.js"
         verb="*"
         preCondition="integratedMode"
         type="System.Web.StaticFileHandler" />

Alternatively put your script into the ~/Scripts/ folder and reference it like such:

@Scripts.Render("~/Scripts/script.js")
Sign up to request clarification or add additional context in comments.

3 Comments

Just a sidenote... I actually put my scripts in the Views folder. I do something like having Views/Home/Contact.cshtml and nested underneath the file in visual studio (using the NestIn extension) I have Views/Home/Contact.js and Views/Home/Contact.less. Then my build script picks up the files appropriately. It's actually a great time saver to do this.
David, can you elaborate about what your build script does? I like this idea too, I am passing a lot of time struggling and looking for related files...
@codea sorry, that was confusing. Since I have a build script that minifies and concatenates my scripts, instead of having it search the scripts folder for scripts—~/Scripts/**/*.js—it searches the Views folder instead—~/Views/**/*.js since they are now stored in there.
10

Its better practice to place your Js file in Script folder and access it from there. You could write this code in view's head to use the js file

@Scripts.Render("~/Scripts/script.js")

Comments

2

you have to add your script in the Bundle config :

 public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",    "~/Views/Home/script.js"));

this worked for me

Comments

1

You should Add rendersection to your Layout Page which your view using.

@RenderSection("scripts", required: false)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.