Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...