开发者

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

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?


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜