Brian Low
Brian Low

Reputation: 11811

ASP.Net MVC3: Place .js files near View instead of Scripts folder

We'd like to split out the javascript from our Razor views (so we can test). Can we locate the .js files near the views they correspond with rather then in the Scripts folder? For example, we'd like to see this in solution explorer:

MyMvcProject
    - Views
      - Home
        - About.cshtml
        - About.js

However, I don't know to references the .js file from the .cshtml view.

Upvotes: 7

Views: 3538

Answers (3)

Alexey Solonets
Alexey Solonets

Reputation: 817

Open Views/Web.config and replace this

<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />

with this

<add name="ExcludeRazorViews" path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler" />

Upvotes: 3

Jesse
Jesse

Reputation: 8393

If your talking about breaking 'custom' scripts out of your view and placing them within a separate folder for the purpose of testing your javascript then yes you can place them in a folder of your choice.

However, I wouldn't recommend placing them side by side your view...that's going to lead to a messy project structure and will make it that much harder if you ever want to minimize your javascript.

I generally leave "framework" javascript files within the Scripts folder for the reasons that Mystere Man mentioned in his answer however, I have put 'custom' or view related javascript files within /Content/js/.

To reference them you would simply add a reference within your view or master page (layout):

<script type="text/javascript" src="@Url.Content("~/Content/js/somelink.js")"></script>

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

For security reasons, asp.net-mvc blocks all file access to the /Views folder from URL's. This can be worked around, but I would suggest NOT doing this for security reasons.

You should generally leave your scripts in Scripts folder, particularly the system-wide ones such as jquery and the unobtrusive stuff. This is so they can be more easily updated through NuGet as new versions or bugfixes are released.

I'm not sure why you have a problem with testing and leaving them in the default location.

Upvotes: 9

Related Questions