Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing js files in the views folder

I am trying to place my javascript files with my views.

I have the following js file location. /Views/Home/Home.js

However, when referenced with a script tag, it results in a 404 error.

As per the following SO question: ASP.NET MVC - Where do you put your .js files if you dont want to store them in /Scripts?

I added file.js to my Register routes. (Did not resolve the problem)

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{file}.js");
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    }

How can i store and reference my js files next to my views?

like image 824
Valamas Avatar asked Mar 08 '12 23:03

Valamas


People also ask

Where should js files be placed?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

HOW include js file in ASP NET MVC?

To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function.

What is more appropriate way to include JavaScript as an external file?

Create external JavaScript file with the extension . js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.


1 Answers

The problem is that, for security reasons the web.config that is inside the Views folder blocks all request to files in that folder. This is what you will find in the config file:

<httpHandlers>
  <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>

And for IIS7:

<handlers>
  <remove name="BlockViewHandler"/>
  <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>

Solution

You can change the wildcard to catch only the .cshtml files.

<httpHandlers>
  <add path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>

<handlers>
  <remove name="BlockViewHandler"/>
  <add name="BlockViewHandler" path="*.cshtml" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>

With this wildcard, the .js files won't be blocked.

like image 154
goenning Avatar answered Oct 04 '22 07:10

goenning