views:

519

answers:

2

Hi,

I am trying to access a .js file in the views directory. I have an MVC application with /Views/Home/MyControl.ascx I have a js file /Views/Home/MyControl.js

I wish to reference the .js file and keep it with the control. I have tried the following entries in the routing, and none seem to work.

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{file}.js");
        routes.IgnoreRoute("{resource}.js/{*pathInfo}");
        routes.IgnoreRoute("{controller}/{resource}.js/{*pathInfo}");
        routes.IgnoreRoute("{*alljs}", new { alljs = @".*\.js(/.*)?" });

Please help, please don't suggest adding the .js file to the scripts directory. I would like to make it work this way, or know why it cannot be done.

I would put the script into the page, only script debugging is broken in VS2010 B2.

Thanks Regards Craig.

+1  A: 

The Views folder is, well for views, and javascript should be put elsewhere. That's why the designers of the MVC framework put a web.config in this Views folder that denies access to any file inside. You could modify this defaut setting but be warned that this could be a potential security hole. So open the web.config file located in the Views folder and:

Replace:

<httpHandlers>
  <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>

with:

<httpHandlers>
  <add path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler"/>
  <add path="*.master" verb="*" type="System.Web.HttpNotFoundHandler"/>
  <add path="*.ascx" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>

Navigate to http://yoursite/Views/test.js

P.S. You could also remove all the IgnoreRoutes you put in global.asax.

Darin Dimitrov
Thanks for the help.This does sound wrong. What if I put the javascript with the controller, would that be a better approach. I don't really want it in the general scripts folder. Would I need the IgnoreRoute for that to work?
Craig
A: 

Wouldn't this be a better solution using the DefaultHttpHandler for html resources and keeping the HttpNotFoundHandler for all other types of file

<httpHandlers>  
  <add path="*.html" verb="*" type="System.Web.DefaultHttpHandler"/> 
  <add path="*.*" verb="*" type="System.Web.HttpNotFoundHandler"/> 
</httpHandlers> 
Clement-Edwin ALBERT