MVC - Accessing css, image, js files in view folde

2019-01-20 07:24发布

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条回答
可以哭但决不认输i
2楼-- · 2019-01-20 07:49

Add this under your views web.config Handlers section

<add name="JavaScriptHandler" path="*.js" verb="*" preCondition="integratedMode" type="System.Web.StaticFileHandler" />
查看更多
狗以群分
3楼-- · 2019-01-20 07:52

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

查看更多
\"骚年 ilove
4楼-- · 2019-01-20 07:53

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.

查看更多
Ridiculous、
5楼-- · 2019-01-20 08:14

You can use a UrlHelper:

<script src="@Url.Content("~/view/account/js/custom.js")" type="text/javascript"></script>
查看更多
登录 后发表回答