19

In my mvc 3 application, assuming I have a folder structure like \Views\Account\js\custom.js How do I add that file to my view in the Account\index.cshtml please?

I have tried:

<script src="js/custom.js" type="text/javascript"></script>
<script src="/views/account/js/custom.js" type="text/javascript"></script>
<script src="~views/account/js/custom.js" type="text/javascript"></script>

but nothing seems to work, firebug always says 404 file not found in places that are nothing like the ones I specify. (sometimes it adds extra view in the path :-s)

I know I can put it outside the view in my own folder and access it like /myFolder/myfile.js and it would work but this javascript file is very intimately related to what's going on in account view and nothing else, so it would make sense to put it there..

thanks.

4 Answers 4

16

The web.config file in the /Views folder restricts all access to files in the folder by default:

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

You could change that, but it's probably more secure overall to not store the assets in the views folder.

Sign up to request clarification or add additional context in comments.

2 Comments

hm... yea, modifying that particular behaviour of web.config seems like a foolish thing to do.. I will just put this js file with the rest of my js files.. thanks very much.
See stackoverflow.com/questions/604883/… for an example of how to explicitly allow just js files to be served from the Views folder.
2

You can use a UrlHelper:

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

1 Comment

Hi, I gave this a go, but it's still coming up as 404.. I tried to look at the resolved path on view-source and it looks correct.. so may be pjumble's answer is correct :(
0

The best way is to use T4MVC - http://mvccontrib.codeplex.com/wikipage?title=T4MVC No need to use magic strings...

3 Comments

yes, I already have that, but the trouble is that my js file is not in scripts or content folder, rather inside a view folder itself, and there isn't anything for me to fetch that file.
You can change the T4 settings file that comes with T4MVC to include folders other than Scripts and Content.
I see.. but even so, as mentioned in pjumbl's answer.. it would still be inaccessible! Thank you though.
0

Add this under your views web.config Handlers section

<add name="JavaScriptHandler" path="*.js" verb="*" preCondition="integratedMode" type="System.Web.StaticFileHandler" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.