将js文件放在views文件夹中 [英] Placing js files in the views folder

查看:25
本文介绍了将js文件放在views文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 javascript 文件放在我的视图中.

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

我有以下 js 文件位置./Views/Home/Home.js

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

但是,当使用脚本标记引用时,会导致 404 错误.

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

根据以下 SO 问题:ASP.NET MVC - 如果您不想将 .js 文件存储在/Scripts 中,您将它们放在哪里?

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?

我将 file.js 添加到我的注册路由中.(没有解决问题)

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}");
    }

如何在视图旁边存储和引用我的 js 文件?

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

推荐答案

问题在于,出于安全原因,Views 文件夹中的 web.config 会阻止对该文件夹中文件的所有请求.这是您将在配置文件中找到的内容:

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>

对于 IIS7:

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

解决方案

您可以更改通配符以仅捕获 .cshtml 文件.

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>

使用此通配符,.js 文件不会被阻止.

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

这篇关于将js文件放在views文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆