ASP.NET MVC - Where do you put your .js files if you dont want to store them in /Scripts?

天大地大妈咪最大 提交于 2019-12-07 05:22:00

问题


I have a number of .js files that I would like to be stored in the same directories as their views (they're specific to a view - its simply to keep the javascript separate from the view's HTML)

However, adding them to the /Views/ControllerName/ directory wont work because when a request is made to the webserver for the .js file:

<script type="text/javascript" src="/Views/ControllerName/myscript.js"></script>

It would essentially be directed at the 'Views' controller which obviously doesnt exist.

Update

From what I have read, adding the following IgnoreRoute in the global.asax.cs RegisterRoutes method should permit access to any requested .js file:

routes.IgnoreRoute("{resource}.js/{*pathInfo}");

However, I cant seem to get it to work?


回答1:


SOLVED

After having found and tested a number of posts (most conclusive post here) that I couldnt get to work, the following solves the puzzle:

In the Global.asax, add the following code to the RegisterRoutes method:

routes.IgnoreRoute("{file}.js");

There is a great post here that describes this and additional activity here




回答2:


You have two options, I think.

  1. Recreate the Views folder structure under scripts and store them in the same relative location in the scripts directory.
  2. Don't keep them in separate files, but use separate ContentPlaceHolders in the MasterPage for a script section (typically at the bottom of the body).

You could also store them in any of the non-"special" folders, but I think scripts is the right place if you are keeping them separate.

I normally keep common scripts (used by more than one page) in the scripts folder, without a corresponding views hierarchy, and page-specific scripts in the view file, but in a separate ContentPlaceHolder. To me the important thing is not to keep the JS in a separate file, but separate from the content. Using a different ContentPlaceHolder accomplishes this.




回答3:


Contemplate that last sentence of yours - might that be why a specific directory (/Scripts/) has been set aside for these? ;)



来源:https://stackoverflow.com/questions/2865388/asp-net-mvc-where-do-you-put-your-js-files-if-you-dont-want-to-store-them-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!