views:

79

answers:

3

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?

A: 

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

Sean Kinsey
A: 

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.

tvanfosson
The reason I want to keep the javascript in a file is because the browser will cache it. Inline javascript cant be cached. Please correct me if im wrong! Thanks
Jimbo
@Jimbo - do you really have enough javascript specific to the page to worry about the browser caching it? Also, don't forget that you'll generate an extra, synchronous request for each javascript file. In my experience I don't have more than a few hundred bytes, certainly not more than 1K bytes of javascript per page. With output compression enabled, it's not worth the annoyance of maintaining separate files.
tvanfosson
Indeed - the scripts for these pages are up to 20kb and the connections the users will be utilizing run at about 1.5 kb/s :(Do you know how to add a route handler to ignore .js file requests?
Jimbo
A: 

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

Jimbo