Asp.net-mvc – Where to put view-specific javascript files in an ASP.NET MVC application

asp.net-mvc

What is the best place (which folder, etc) to put view-specific javascript files in an ASP.NET MVC application?

To keep my project organized, I'd really love to be able to put them side-by-side with the view's .aspx files, but I haven't found a good way to reference them when doing that without exposing the ~/Views/Action/ folder structure. Is it really a bad thing to let details of that folder structure leak?

The alternative is to put them in the ~/Scripts or ~/Content folders, but is a minor irritation because now I have to worry about filename clashes. It's an irritation I can get over, though, if it is "the right thing."

Best Answer

Old question, but I wanted to put my answer incase anyone else comes looking for it.

I too wanted my view specific js/css files under the views folder, and here's how I did it:

In the web.config folder in the root of /Views you need to modify two sections to enable the webserver to serve the files:

    <system.web>
        <httpHandlers>
            <add path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
            <add path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
            <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>
        <!-- other content here -->
    </system.web>

    <system.webServer>
        <handlers>
            <remove name="BlockViewHandler"/>
            <add name="JavaScript" path="*.js" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
            <add name="CSS" path="*.css" verb="GET,HEAD" type="System.Web.StaticFileHandler" />
            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
        <!-- other content here -->
    </system.webServer>

Then from your view file you can reference the urls like you expect:

@Url.Content("~/Views/<ControllerName>/somefile.css")

This will allow serving of .js and .css files, and will forbid serving of anything else.