将与一个页面或 View 唯一关联的 JavaScript 文件放置在该页面或 View 所在的同一文件夹中是我公司的一个标准。现在我们正在迁移到 MVC,我们希望继续这样做。例如,如果有一个文件
~/Views/Customer/CustomerMgmt.cshtml
我需要能够引用以下关联的脚本文件:
~/Views/Customer/CustomerMgmt.js
这个js文件的功能是仅限 与 CustomerMgmt.cshtml 相关的文件不会被共享,因此其他消费者不会使用它。如果我使用以下内容引用 JavaScript 文件,则会失败并出现 404 错误:
<script type = "text/JavaScript" src = "@Url.Content( "~/Views/Customer/CustomerMgmt.js" )">< /script>
我研究后尝试的解决方案包括:
< add name="BlockViewHandler"path=""verb=""preCondition="integratedMode"type="System.Web.HttpNotFoundHandler"/>
此选项允许我引用 ~/Views/Customer/CustomerMgmt.js 但它不安全
< add name="JavaScriptHandler"path=".js"动词=""preCondition="integratedMode"type="System.Web.StaticFileHandler"/>
我仍然收到 404 错误。
我选择使用以下修改 ~/views/web.config 的说明:
< add name="JavaScript"path="*.js"动词="GET,HEAD"type="System.Web.StaticFileHandler"/>
< add name="CSS"path="*.css"动词="GET,HEAD"type="System.Web.StaticFileHandler"/>
< add path="*.js"动词="GET,HEAD"type="System.Web.StaticFileHandler"/>
< add path="*.css"动词="GET,HEAD"type="System.Web.StaticFileHandler"/>
<添加路径=“*”动词=“*”类型=“系统.Web.HttpNotFoundHandler”/>
进行此更改后,我收到 500 错误和以下内容(简而言之):
已检测到不适用于集成托管管道模式的 ASP.NET 设置
我收到了以下建议:
一种。将配置迁移到 system.webServer/handlers 部分
湾。通过设置
C。将应用程序切换到经典模式应用程序池
使用选项“b”后,一切似乎都正常,我可以引用 ~/Views/Customer/CustomerMgmt.js,但我看到一些帖子表明这不是最好的方法。
我的问题是:
我知道我也可以创建一个新的文件夹结构,如“~/ViewScripts/...”,并将相关的 js 文件放在那里。如有必要,我会这样做,但如果可能的话,我想继续遵守公司标准并将仅由特定 View 使用的文件与该 View 一起放置。
提前感谢大家。我研究的一些项目包括:
MVC - Accessing css, image, js files in view folder
Placing js files in the views folder
How to reference javascript file in ASP.NET MVC 2 Views folder?
Where to put view-specific javascript files in an ASP.NET MVC application?
Cannot load resource MVC 4 JavaScript
Can I deploy a javascript file within MVC areas?
Serving static file on ASP.NET MVC (C#)
Serving static file on ASP.NET MVC (C#)
最佳答案
来自 this forum我设法得到了一些似乎可以完成这项工作的代码。我在 ViewComponent 中使用它。我有一个组件文件夹,并希望将所有文件合并到一个文件夹中,例如
假设一个一致的命名约定,我用这个加载它,它不需要对 web.config 进行任何更改,也不会打开客户端来加载其他 .js 文件。
<script>
@{ Html.RenderPartial(Regex.Replace(ViewContext.ExecutingFilePath, @"\.[^.]+$", @".js")); }
</script>
关于javascript - 引用 View 文件夹中的 JavaScript 文件 - MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40496110/