开发者

In ASP.NET MVC, adding a script reference throws exception

On a skeleton ASP.MVC that Visual Studio creates, I add a script tag to my head section in Site.Master:

<script src="~/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

This causes the page to not render. In my case, I had a custom controllerfactory and the base method GetControllerInstance threw an exception:

The controller开发者_运维知识库 for path '/~/Scripts/jquery-1.3.2.js' could not be found or it does not implement IController.

Using "../../Scripts/jquery-1.3.2.js" for the src does not work either.

The only way it works is:

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>"
    type="text/javascript"></script>

Then of course, the intellisense does not work for jquery. So I have to resort to adding the hack:

<% if (false) { %>
    <script src="~/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<% } %>

which the hotfix was supposed to fix according to ScottGu

A line above is a link to a stylesheet:

<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />

For some reason, that works fine. Whether I use the virtual or relative path, I can see that the resulting url on the page is "Content/Site.css". The same can't be said for the jquery url. jquery link is returned as is - the jquery url is returned on the page containing the "~" or the "../..".

Can someone tell me what is going on? Thanks

UPDATE:

Thanks to the commenters, I remembered that ~ is an asp.net thing. My only question is then why doesn't the same issue exist for the stylesheet? The link tag above, for example, I can put ~ or relative paths and it always comes out right. Where is the magic?


Have you tried without the ~:

<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

The ~ character is used only by server side processing scripts indicating the root of the web site. The reason:

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script>

works is because it is translated to:

<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>


The "~" is not supported within standard HTML - it is an ASP.NET shortcut. So you've either got to do it the way you specified in your OP and the hack for intellisense, or as Darin specified but then you lose the ability to automatically pick up your VRoot.


I don't know for sure, but maybe MVC is smart enough to not include CSS files in the routing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜